gcc - Use the first occurred implementation when linking C programs -
i have a.h , a.c gives interface , implementation of function
//a.h #ifndef a_h #define a_h int op(); #endif //a.c #include "a.h" int op(){ return 1; }
similarly, have b.h , b.c gives interface of function of same name different implementation
//b.h #ifndef b_h #define b_h int op(); #endif //b.c #include "b.h" int op(){ return 2; }
now, want link them main program
#include <stdio.h> int op(); int main(){ printf( "returned = %d\n ", op()); }
for purpose, first compile a.c , b.c a.o , b.o respectively.
gcc -c a.c; gcc -c b.c
then trying link them together. usual objective here let main.c choose implementation of 'op' using implementation appears first in linking command. so, ideally:
gcc a.o b.o main.c
should give me executable returns 1 when executed, , gcc b.o a.o main.c
should give me executable returns 2 when executed. error message
ld: 1 duplicate symbol architecture x86_64
to not surprised. question is: how can let first occurred implementation used main.c? thanks.
one option:
make 2 static libraries -- 1
a.o
, 1b.o
.ar liba.a a.o ar libb.a b.o
in link line, use library want given higher priority before other one.
gcc main.c -l. -la -lb
Comments
Post a Comment