1
votes

I am trying to learn C++/CLI, with the plan of writing a DLL which will be consumed by (unmanaged) C code. However, I cannot get the most basic example to build, as is reproducible below:

I am working in Visual Studio Express 2013.

Create new project -> CLR ->class library

LearnCli.h:

extern "C" __declspec(dllexport) 
int __stdcall TestFunc();

LearnCli.cpp:

#include "stdafx.h"
#include "LearnCli.h"
int __stdcall TestFunc()
{
    return 3;
}

Build with no problems.

Add Project -> Win32 ->Console Application

From the context menu in solution explorer for the new console project:

Add -> reference -> LearnCli

stdafx.h

#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
#include "..\LearnCli\LearnCli.h"

ConsoleApplication.cpp

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int z;
    z=TestFunc();
    cout << "Function returns:" << z << endl;
    cin.get();
    return 0;
}

intellisense has no problems, but on build:

Error   1   error LNK2019: unresolved external symbol _TestFunc@0 referenced in function _wmain [path]\Projects\LearnCli\ConsoleApplication1\ConsoleApplication1.obj    ConsoleApplication1

What am I missing which is not allowing the win32 console app to find the function? Cheers.

Edit

Thanks to the comment and link, I have change the LearnCli.h file to

#ifdef LEARNCLIAPI_EXPORTS
#define LearnCliApi_DECLSPEC __declspec(dllexport)
#else
#define LearnCliApi_DECLSPEC __declspec(dllimport)
#endif

And gone to Project -> Properties -> C/C++ -> Preprocessor ->Definitions and added LEARNCLIAPI_EXPORTS. unfortuately the error is unchanged

1
When your test program #includes the .h file, it is still declared dllexport. That's not correct of course, it now needs to be dllimport. Read this, note the use of the EXPORTING macro. - Hans Passant

1 Answers

1
votes

You need to link your application(exe) project with the .lib built from dll project.

You can add that from Project settings >> Linker >> Input files or simply put a line on your source.

i.e.

pragma(comment, "lib:<your_lib.lib>")