Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static linking of C++ code

I have the following problem: I use some classes like the following to initialize C libraries:

class Hello
{
public:
  Hello()
  {
    cout << "Hello world" << endl;
  }

  ~Hello()
  {
    cout << "Goodbye cruel world" << endl;
  }

} hello_inst;

If I include this code in a hello.cc file and compile it together with another file containing my main(), then the hello_inst is created before and destroyed after the call to main(). In this case it just prints some lines, in my project I initialize libxml via LIBXML_TEST_VERSION.

I am creating multiple executables which share a lot of the same code in a cmake project. According to this thread: Adding multiple executables in CMake I created a static library containing the code shown above and then linked the executables against that library. Unfortunately in that case the hello_inst is never created (and libxml2 is never initialized). How can I fix this problem?

like image 312
hfhc2 Avatar asked Nov 13 '22 04:11

hfhc2


1 Answers

I had a similar problem and solved it by defining my libraries as static. Therefore I used the following code:

add_library( MyLib SHARED ${LBMLIB_SRCS} ${LBMLIB_HEADER})

Maybe this fixes your problem

like image 196
tune2fs Avatar answered Nov 15 '22 05:11

tune2fs