简体   繁体   中英

Why new VS2013 project's functions are unresolved in linking if file is .cpp, but ok if file is .c

I'm linking all the native libs to a .dll which is used in WPF application.

I'm done this with other projects that are compiled to libs but the latest one does not work somehow, although all seems to be same way. I did like this:

.h:

#ifndef MYHEADER_H_
#define MYHEADER_H_

#ifdef __cplusplus
extern "C" {   
#endif

void  MySetLoginResultCallback(int(*Callback)(int Ok, const char *UserName));


#ifdef __cplusplus
} // end of extern "C"
#endif
#endif // MYHEADER_H_

.cpp:

typedef int(*LoginResultCB_t)(int IsOk, const char *UserName);
LoginResultCB_t             gLoginResultCB;

void MySetLoginResultCallback(LoginResultCB_t pCB)
{
    gLoginResultCB = pCB;
}

extern "C" __declspec(dllexport) int MyLoginResultCB(int Ok, cons char *UserName)
{
   if (gLoginResultCB)
       return gLoginResultCB(Ok, UserName);

   return -1;
}

MyLoginResultCB is imported to WPF exe and called from there. In initialization the MySetLoginResultCallback is called from a C-file in native .dll.

In .dll linking I get unresolved error from MySetLoginResultCallback (which is called in native .c file). If I leave the header exactly the same and rename .cpp -> .c and remove extern "C" the .dll linking succeeds. What am I missing here?

call from aini.c

MySetLoginResultCallback(XpAfterLoginCB);

error:

1>aini.obj : error LNK2019: unresolved external symbol _MySetLoginResultCallback referenced in function _InitNoAKit

In your .cpp file, you're defining a function MySetLoginResultCallback with C++ language linkage. That's a different function than the function MySetLoginResultCallback with C language linkage declared in the .h file.

The correct solution would be to add C language linkage to the .cpp file:

extern "C" {

typedef int(*LoginResultCB_t)(int IsOk, const char *UserName);
LoginResultCB_t             gLoginResultCB;

void MySetLoginResultCallback(LoginResultCB_t pCB)
{
    gLoginResultCB = pCB;
}

}

Notice that function types have language linkage too, which means that the typedef LoginResultCB_t has to be declared with C language linkage in the .cpp file also, because the parameter is declared as such in the .h file.

The reason the way that extern "C" definitions ONLY in .h file worked in other projects/libs is that I included my header file with function declarations in my .cpp file with the definitions. Thanks to @molbdnilo to point this out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM