Library not linked correctly (at all?)

I want a class to register itself to an other class at runtime before the main() is run.

I tried several appreaches which all worked fine, when alle src files are directly used for the binary.

But when I move one class to an library it doesnt work anymore and the register/init isnt called anymore. I even think the library isnt linked at all.

Here is a small code example:

main.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
	cout << "Main says hello!" << endl;
	return NULL;
}


class1.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>

static bool do_init(void)
{
    std::cout << "Init: 1" << std::endl;
	return true;
}

static bool pre_init = do_init();


class2.cpp
1
2
3
4
5
6
7
8
9
#include <iostream>

static bool do_init(void)
{
    std::cout << "Init: 2" << std::endl;
	return true;
}

static bool pre_init = do_init();


CMakeLists.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
CMAKE_MINIMUM_REQUIRED(VERSION 2.4)
PROJECT(Test)

#########################################

add_executable(testBinNoLib FirstFile.cpp Main.cpp SecondFile.cpp )

#########################################

add_executable(testBinStaticLib FirstFile.cpp Main.cpp )

add_library(libStatic SecondFile.cpp )

target_link_libraries(testBinStaticLib libStatic )

#########################################

add_executable(testBinSharedLib FirstFile.cpp Main.cpp )

add_library(libShared SHARED SecondFile.cpp )

target_link_libraries(testBinSharedLib libShared)


3 Binarys are created:

The first works properly under win/linux
The one with the shared library works properly under linux
And the one with the static library doesnt work on any os correctly

Anybody got an idea, I would be very thankful!
Nobody got an Idea? I think the problem is, that the compiler recognizes that the binary doesn't need the library at all and therefor optimizes it by not linking the library at all.

But how can I force that it is linked nevertheless?
Last edited on
Your assumption is correct - you need to reference at least one symbol from the module that you want to be linked to your application.
The thing is, that the module shall register itself to the main program, so the main program hasn't got any knowledge about the module. Is there a possibilty to achieve this functionality?
I got the same problem. i think it links the objects in shared libraries (since the compiler can't know what symbols will be used by the dependant applications), but not for static libraries. Unless you can make your 'plugins' a dynamic library, you will have to reference them at least once.
Topic archived. No new replies allowed.