akris
akris

Reputation: 57

Function in .lib is defined but when i generate .so from same .lib the function is not present

I have a lib1.lib which has function fun1() which shows defined when i do nm. I have created my.so out of my.lib. But when i search my.so That fun1() is not there at all.since there might be no callers compiler might be ignoring it. So i created some dummy array like

char* dummyArray={
 &fun1;
};

in the file where fun1() is defined. But this also does not work. Kindly help.

Upvotes: 2

Views: 42

Answers (2)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

You need to force the compiler and linker to fetch the function from the library. In your current attempt, you reference a character called fun1 in your program. Because your fun1 is a char, the compiler has no reason to declare a symbol in your .o file that is a function called fun1. As a result, function fun1 will not be fetched from the library and there is no function fun1 in your executable.

(Note that in your example, there is no char fun1 declared, so your compiler should complain. Did you turn warnings on???)

To force the compiler and linker to load the function fun1 from the library, you can write:

char *fun1(void);    // prototype;

char *(*p)(void)     // p is a pointer to a function with same signature as fun1...
     = fun1;         // and we initialize it with function 'fun1'

Note: should the compiler determine that you never use p, it still may remove the function pointer variable and the assignment of fun1 to it, so fun1 would still not have been loaded.

Upvotes: 1

yugr
yugr

Reputation: 21878

Just wrap

-Wl,--whole-archive -lyourlib -Wl,--no-whole-archive

when linking .so. For background see c-differ-between-linking-with-o-and-with-a-file-different-behavior-why

Upvotes: 1

Related Questions