Failure of an external link variable inside a static library

I need to use an ugly C library inside my C ++ application. In the following explanation, I will call it UglyLib. I have successfully compiled UglyLib as a statically linked library. In the ugly.h file, UglyLib uses an external variable:

ugly.h file:

extern SomeStruct_type somestruct;

      

the variable is defined (and also used) in another file. I will call it anotherugly.c.

file anotherugly.c:

SomeStruct_type somestruct;

      

My C ++ - The application is based on a shared template library (TemplateLib), and the application itself is composed primarily of a GUI and application library statically linked to the main window code. I will call this statically linked library ApplicationLib.

TemplateLib contains templatelibfile.h which exports the foo function using somestruct, an external variable exposed by UglyLib.

templatelibfile.h file:

#include<ugly.h>
...
void foo()
{
...
do something with somestruct
...
}

      

The foo function is used by appllibfile.h contained in a statically linked ApplicationLib.

file appllibfile.h:

#include<templatelibfile.h>
...
void applfoo()
{
...
foo();
...
}

      

The Main Window application includes an appllibfile.h file

file main.cpp:

#include<appllibfile.h>
...
int main()
{
...
applfoo();
...
return 0;
}

      

In VS2008, when I try to compile my main window application, microsoft linker gives me this error

error LNK2001: unresolved external symbol "struct SomeStruct_type somestruct" (? somestruct @@ 3USomeStruct_type @@ A)

If I add a new definition of the extern variable to templatefile.h, the compiler stops complaining.

templatelibfile.h file:

#include<ugly.h>
SomeStruct_type somestruct
...
void foo()
{
...
do something with somestruct;
...
}

      

BUT I would like to avoid this because I don't know if this is the right way to do it (I don't want to risk changing the semantics of UglyLib overriding another instance of somestruct). Do you have any suggestions to avoid the linking problem without overriding the external extern variable? Many thanks!

+3


source to share


1 answer


This is probably due to the fact that the C ++ compiler works with names. Since it anotherugly.c

is a C source (presumably compiled with a C compiler), the symbol somestruct

will display without corruption. When you compile the rest of the files with the C ++ compiler, the linker looks for a malformed name that doesn't exist.



I think that an enclosing declaration in ugly.h

in extern "C"

can solve the problem.

+4


source







All Articles