Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a shared library with main() [duplicate]

In glibc (and also EGLIBC I believe), the libc.so library has a main() method:

$ /lib/i386-linux-gnu/libc.so.6
GNU C Library (Debian GLIBC 2.19-18+deb8u1) stable release version 2.19, by Roland McGrath et al.
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
Compiled by GNU CC version 4.8.4.
Compiled on a Linux 3.16.7 system on 2015-08-30.
Available extensions:
        crypt add-on version 2.1 by Michael Glad and others
        GNU Libidn by Simon Josefsson
        Native POSIX Threads Library by Ulrich Drepper et al
        BIND-8.2.3-T5B
libc ABIs: UNIQUE IFUNC
For bug reporting instructions, please see:
<http://www.debian.org/Bugs/>.

Now I want to do the same with the following minimalistic example (i. e. I want my own SO to also have a main()):

#include <stdio.h>

int main(int argc, char *argv[]) {
        printf("Hello, World!\n");
        return 0;
}

Linking as a regular executable:

$ gcc -g -O0 -Wall -c test.c
$ gcc -o test test.o
$ ./test
Hello, World!

Now linking as a shared object:

$ gcc -g -O0 -Wall -c test.c
$ gcc -shared -o libtest.so test.o
$ ./libtest.so
Segmentation fault
  • nm shows that main symbol is present (000004f5 T main)
  • When debugging, gdb doesn't show any meaningful backtrace.
  • Adding -fpic or -fPIC to the gcc command line doesn't help.

What am I doing wrong?

like image 930
Bass Avatar asked Jan 26 '26 10:01

Bass


1 Answers

the libc.so library has a main() method

No, the implementation of C library of gcc has an entry point not a main symbol.

You can find an example of how to do this here.

like image 91
Stargateur Avatar answered Jan 28 '26 22:01

Stargateur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!