I have C static library that has a struct global variable defined within it. I wish to access that variable within C++ code that will link to that C library. At the moment, I am getting "ld: symbol(s) not found for architecture x86_64" errors.
I am trying the following (simplified struct for the sake of the question):
// library.h
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int simpleVariableA;
int simpleVariableB;
} GlobalStruct;
extern GlobalStruct gs;
#ifdef __cplusplus
}
#endif
// library.c
#include "library.h"
GlobalStruct gs;
Library.c and library.h are compiled into library.a, a statically-linked library. I then want to link a C++ file to the library, but get errors.
// main.cpp
#include "library.h"
int main(int argc, char** argv) {
gs.simpleVariableA = 1;
gs.simpleVariableB = 1;
}
What am I doing wrong? I have run "nm -g library.a" and get "0000000000000008 C _gs" back, so I think this means that the symbol is being exported, no? Is it an issue with C++ not finding C code?
I compile the files like this:
gcc -c library.c -o library.o
ar rcs liblibrary.a library.o
g++ main.cpp -L. -llibrary
BTW, I get an error with the ar command:
warning: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib: warning for library: liblibrary.a the table of contents is empty (no object file members in the library define global symbols)
However, this error goes away if I define a function f() in library.h and library.c and compile this into the library.