Howcome some C ++ functions with C-linked unspecified linking?

This is what makes me rather perplexed.

I have a C ++ file that implements a set of functions and a header file that defines prototypes for them.

When building with Visual Studio or MingW-gcc, I get linking errors on two of the functions and adding the "extern" C "'qualifier resolved the error, how is this possible?

Header file, "some_header.h":

// Definition of struct DEMO_GLOBAL_DATA omitted

DWORD WINAPI ThreadFunction(LPVOID lpData);
void WriteLogString(void *pUserData, const char *pString, unsigned long nStringLen);
void CheckValid(DEMO_GLOBAL_DATA *pData);
int HandleStart(DEMO_GLOBAL_DATA * pDAta, TCHAR * pLogFileName);
void HandleEnd(DEMO_GLOBAL_DATA *pData);

      

C ++ file, "some_implementation.cpp"

#include "some_header.h"

DWORD WINAPI ThreadFunction(LPVOID lpData) { /* omitted */ }
void WriteLogString(void *pUserData, const char *pString, unsigned long nStringLen) { /* omitted */ }
void CheckValid(DEMO_GLOBAL_DATA *pData) { /* omitted */ }
int HandleStart(DEMO_GLOBAL_DATA * pDAta, TCHAR * pLogFileName) { /* omitted */ }
void HandleEnd(DEMO_GLOBAL_DATA *pData) { /* omitted */ }

      

The implementations compile without warnings, but when linking to the UI code that calls them, I get normal

error LNK2001: unresolved external symbol "int __cdecl HandleStart(struct _DEMO_GLOBAL_DATA *, wchar_t *)
error LNK2001: unresolved external symbol "void __cdecl CheckValid(struct _DEMO_MAIN_GLOBAL_DATA *

      

What really confuses me is that only these two functions (HandleStart and CheckValid) seem to be built with a C reference. By explicitly adding "extern" C '' declarations for only these two, the bind error is resolved and the application builds and runs. Adding "extern" C "to some other function, such as HandleEnd, introduces a new linking error, so it obviously compiled correctly.

The implementation file never changes in any of them, only in prototypes.

+2


a source to share


2 answers


The error indicates that nothing is happening to your implementation file or file (as used by the implementation file). The link error indicates that the generated functions were generated using C ++ linkage. Its UI file incorrectly searched for C-Linkage Feature Options. Correcting the definitions in the title fixes your implementation to match possibly the wrong user interface requirements, and not vice versa.

Your user interface file is a .m or .c file, OR if your user interface file is a .cpp file you have a dome like this:



// ui.cpp
extern "C" {
#include "some_header.h"
}

      

Of course, if your user interface file is a .c file - you need to either change it to cpp or explicitly define the functions with C-linkage so that they can be called from C.

+1


a source


Can function names conflict with names declared in the header?



Are you having the same problem if you give a function different names?

+1


a source







All Articles