Undefined Links after a link to a static library

I wrote a simple program to check if xdotool can fulfill my requirements. (Well, not really. My first step is to make sure I can call the xdotool library.)

#include <xdo.h> #include <iostream> using namespace std; int main(){ cout << xdo_version() << endl; xdo_new(NULL); return 0; } 

However, when I compile this with g++ -oa main.cpp libxdo.a -lXtst -lX11 -lXinerama -I ../test/xdotool-2.20110530.1 , I get the following error message:

 /tmp/ccW95RQx.o: In function `main': main.cpp:(.text+0x5): undefined reference to `xdo_version()' main.cpp:(.text+0x29): undefined reference to `xdo_new(char*)' collect2: error: ld returned 1 exit status make: *** [sendkey] Error 1 

I did not use development packages from apt-get install, because it installs a dynamic library. So, I did apt-get source and built the library myself. I checked that xdo_version and xdo_new are specific functions in the static library by executing the following commands:

 $ nm libxdo.a | grep xdo_version 00000000000002b0 T xdo_version $ nm libxdo.a | grep xdo_new 0000000000004070 T xdo_new 0000000000003c90 T xdo_new_with_opened_display 

If I am not mistaken, T in addition to the name of the symbol means that the function is defined.

In conclusion, I am trying to compile the above C ++ code snippet and statically bind it to xdotool, but I encountered some errors as mentioned above.

+4
source share
2 answers

Hint: if the linker shows the signature of the function, then he knows the signature of this function. What does it mean? This means that it was somehow encoded in the function name at compile time, i.e. e. you are a victim of C ++ name mangling .

It seems that the xdo.h header xdo.h not contain guarantees for the case when the C code is compiled as C ++. Declare the functions as extern "C" manually for yourself, then recompile and it will work.

+5
source

Here are some tips for using a dynamic g ++ library, from coding to running.

Application code main.cpp

 #include <iostream> using namespace std; extern "C" int funct(const int in); int main(int argc, char** args){ cout << "test message " << funct(5) << endl; return 0; } 

Libtest.cpp function code

 #include <iostream> using namespace std; extern "C" int funct(const int in){ return in*in; } 

Creating the .so libtest.so file

 g++ -fPIC -c libtest.cpp g++ -shared -o libtest.so libtest.o 

Creating the main application

 g++ -L. main.cpp -o main -ltest 

Application launch set environment variable

@bash: export LD_LIBRARY_PATH =: $ LD_LIBRARY_PATH

@tcsh: setenv LD_LIBRARY_PATH: $ LD_LIBRARY_PATH

Run it !!!

 ./main test message 25 
0
source

Source: https://habr.com/ru/post/1482203/


All Articles