Search code examples
c++-cliinteropwrapperlinker-errorsstatic-linking

Linker error when calling function in native C++ from a c++/cli project


I am trying to call functions in c++ from C# and to do this, I created a C++/CLI project to wrap C++ codes.

My code compiles, but during linkage, I am getting error that linker can not find methods which are defined in c++ code.

The c++ code is a static library and I add a reference to it in C++/CLI project (common properties -> framework and references -> add new reference)

My questions:

  1. Is there anything else should I do?
  2. is adding reference in this sections means that the reference is a .net assembly? Or could it be a reference to a static library.

Edit 1

I am sing VS 2012 on windows 7 64bit

Linker Error:

Error   3   error LNK2019: unresolved external symbol "public: static class MyFile __cdecl MyFile::ReadMyFile(char *)" (?ReadMyFile@MyFile@@$$FSA?AV1@PAD@Z) referenced in function "public: static class MyFileWrapper::MyFileWrapper ^ __clrcall MyFileWrapper::MyFileWrapper::ReadMyFile(class System::String ^)" (?ReadMyFile@MyFileWrapper@1@$$FSMP$AAV11@P$AAVString@System@@@Z)  MyFileWrapper.obj

Solution

  • You didn't post the linker error message, that makes it difficult to answer this question accurately. The most common causes:

    • Forgetting to tell the compiler that the function is a native function and not a managed one. You can tell from the linker error message when you see it using the __clrcall calling convention, native code normally uses the __cdecl calling convention. You fix that by putting #pragma managed(push, off) before the #include, #pragma managed(pop) after it.

    • Trying to link a static library that was compiled with /clr in effect. That's not supported without otherwise drawing a complaint about that when you build the library, unfortunately. The equivalent is already well supported by the CLR, it binds libraries at runtime. You fix that by creating a class library project instead so you'll get a DLL after building it. Use Add Reference to import the declarations from that assembly instead of using #include.

    • Forgetting to tell the linker that it needs to link an unmanaged static library or import library. Using Add Reference is supported in VS2010 and up, on earlier versions of VS you need to use the Linker, Input, Additional Dependencies setting or use #pragma comment(lib, "name") in your source code.