Frank Bergemann Frank Bergemann - 3 months ago 10
C++ Question

Link shared library with main() to executables providing a handler function only

How can I provide a shared library including the

main()
routine for creating executables, that provide only a handler() routine?

frank@frank-M470-2:/media/Workspace/eclipse/libMain$ cat Makefile

main.so: main.cpp
gcc -shared -o main.so -fPIC main.cpp

libMain.so: main.so
gcc -shared -o libMain.so main.so

test1: libMain.so test1.o
g++ -o test1 test1.o -L. -lMain

test2: libMain.so test2.o
g++ -o test2 test2.o -L. -lMain

all: test1 test2

clean:
rm -f test1 test2 libMain.so *.o *.so

frank@frank-M470-2:/media/Workspace/eclipse/libMain$ cat main.cpp

void DoSomething(void);

int main(int, char **)
{
DoSomething();
return 0;
}

frank@frank-M470-2:/media/Workspace/eclipse/libMain$ cat test1.cpp
#include <iostream>

void DoSomething(void)
{
std::cout << "hello from test1" << std::endl;
}

frank@frank-M470-2:/media/Workspace/eclipse/libMain$ cat test2.cpp
#include <iostream>

void DoSomething(void)
{
std::cout << "hello from test2" << std::endl;
}


This works:

> g++ -o test1 test1.o main.so

Because main() is in main.so
But it's not available anymore in libMain.so (?!)

Answer

There's nothing technically wrong with putting the main function in a shared library, as long as it somehow ends up "in" your final executable. It's weird, and unconventional, and probably very confusing, but technically there's no reason that it shouldn't work.

But what you have here are two shared libraries - libMain.so and main.so. The former doesn't actually do anything except link to the latter. The problem is that a shared library doesn't "include" another shared library — it just extends the dependency tree. It doesn't "contain" any functions. Those functions are still found only in main.so.

So, your final executable must link against main.so as well.

I'd recommend losing libMain.so altogether, since it's not doing anything. And if you use gcc (rather than g++) to compile C++ code, you're not going to be linking the C++ standard library runtime, so fix that too.