Frank Bergemann Frank Bergemann - 1 year ago 100
C++ Question

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

How can I provide a shared library including the

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

frank@frank-M470-2:/media/Workspace/eclipse/libMain$ cat Makefile main.cpp
gcc -shared -o -fPIC main.cpp
gcc -shared -o

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

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

all: test1 test2

rm -f test1 test2 *.o *.so

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

void DoSomething(void);

int main(int, char **)
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

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

Answer Source

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 - and 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

So, your final executable must link against as well.

I'd recommend losing 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download