I have a strange problem: the code bellow perfectly compiled.
src.cpp:
extern "C" {
#include "header.h"
}
void A::Execute() {
B::Instance().Reset(ix);
c_func(ix);// this is c functions declared in header.h
C::Instance().Erase(ix);
}
But when I comment out the c_funk() I get linkage error in all places where I use c functions from the header.h file.
With that minor change:
void A::Execute() {
B::Instance().Reset(ix);
//c_func(ix);// this is c function declared in header.h
C::Instance().Erase(ix);
}
I get: undefined reference to c_func().
Any ideas how to solve it? Thanks.
Update:
I have added a dummy function to header.h: foo_for_linkage_problem();
and in such way solved the problem. As I understand the linker try to make some optimization that couses this problem. new code:
void A::Execute() {
B::Instance().Reset(ix);
foo_for_linkage_problem();// this is c empty function declared in header.h
C::Instance().Erase(ix);
}
tldnr: You have problem in the order the libraries are provided to linker.
I think that I know what is wrong. Let's assume that you have four files:
main.c
:main2.c
:a.c
:b.c
:We create
liba.a
andlibb.a
:Now we compile our exec:
And everything works just fine
I get:
let's examine which symbols my libraries provides/requires:
Symbol type
T
means that this library have filea.o
which provides symbola
libb.a
contains fileb.o
which provides symbolb
but requires symbola
The linker does not include whole static library when asked. It looks which
.o
files are needed and links only those. Thus the order you provide the files is crucial.When I executes following command,
main.c
gets compiled and it needs botha
andb
symbols. When linker getsliba.a
library it linksa.o
file because it providesa
symbol. When linker getslibb.a
library it linksb.o
file because it providesb
symbol. Everything works fine.When I executes the main2 command,
main2.c
gets compiled and it needs onlyb
symbols. When linker getsliba.a
it does not linka.o
becuasea
is not needed at all. Then linker getslibb.a
library it linksb.o
file because it providesb
symbol. But theb.o
file needs symbola
, and it is too late to linka.o
,liba.a
was already processed. Note that when I switch libraries it will compile cleanly: