I’ve created some simple basic code to illustrate my problem.
header.h:
#ifdef __cplusplus
# define API extern "C"
#else
# define API
#endif
void callback();
API void libFunction();
testlib.c:
#include "header.h"
void libFunction()
{
Callback();
}
I compile this as a static library like so:
gcc -c testlib.c
ar rsc libtest.a testlib.o
Then my sample c++ code is
main.cpp:
extern "C"{
#include <lib/header.h>
}
#include <stdio.h>
main()
{
libFunction();
}
void Callback()
{
printf("Callback is called \n");
}
and I try to build my exe as so
g++ -I. -L. main.cpp -ltest
and get the following error
./lib/libtest.a(testlib.o): In function `libFunction':
testlib.c:(.text+0x7): undefined reference to `Callback'
collect2: ld returned 1 exit status
I have spent literally all day trying to figure out why. Can anyone please help?
If you want to call
Callbackfrom a C file, it needs to be builtextern "C"in your C++ file – otherwise C++ name mangling will cause the symbols to not line up. You need to change the definition ofCallback()inmain.cppto be:You have a case mismatch, too. The prototype in your header says
callback, but everywhere else you useCallback. On re-reading your code, I think just fixing this case mismatch will solve all your problems. I didn’t see theextern "C"wrapper around the#include <lib/header.h>on first reading.