I'm trying to compile an executable file which i want also to use as shared library. When i'm clearly compile and linking it as "executable" - everything fine - file could start and work correctly. At this phase i cant correctly linking other libraries with it (tons of redefinitions in log). When i'm trying to add options -Fpic -shared - program copiles successfully, but starting with segmentation fault. How can i make it executable and "sharedlibrary" at the same time?
Asked
Active
Viewed 5,906 times
5
-
Can you show the errors? I have compiled libraries and executables under linux with `shared library` enabled, and didn't have the issues you describe. So it is possible. – Noam Rathaus Dec 26 '13 at 10:18
-
1A single file cannot be both an executable and a shared library. – n. m. could be an AI Dec 26 '13 at 10:20
-
1Why do you want to do that? The only example is `/lib/libc.so.6` ... – Basile Starynkevitch Dec 26 '13 at 10:37
-
i've got some "solution" i'm just building my module as shared library with -rdynamic option. – qmor Dec 26 '13 at 12:35
-
Apparently I was wrong and @JohnZwick was too. See [here](http://stackoverflow.com/questions/1449987/building-a-so-that-is-also-an-executable). – n. m. could be an AI Dec 27 '13 at 12:15
1 Answers
7
A single file cannot be a shared library and an executable at the same time. But you can link your object files twice to make both. It'd go something like this:
g++ -c -o module.o module.cpp # create an object that has no main()
g++ -shared -fPIC -o libmodule.so module.o # build shared library
g++ -o program module.o main.cpp # build executable
Or instead, the last line could link the shared library (in which case you'll need the library present when you run the executable):
g++ -o program -l module main.cpp

John Zwinck
- 239,568
- 38
- 324
- 436
-
6This is wrong: on many systems `libc.so.6` is both a shared library and an executable program. – Basile Starynkevitch Dec 26 '13 at 11:13
-
2Technically correct--the best kind of correct! But anyway, 99.99% of executables are not shared objects and vice versa. Let's say you "can" but also you "probably won't." I also tried executing my libc on Mac OS X, and it cannot. – John Zwinck Dec 26 '13 at 11:29
-
6This answer is incorrect (at least on linux): see http://stackoverflow.com/a/1451482/50617 – Employed Russian Aug 03 '14 at 15:58