开发者

GCC outputs an executable ELF file when I want a shared library

开发者 https://www.devze.com 2023-03-04 18:02 出处:网络
I\'m trying to build a shared library in Cygwin using an i686-elf cross-compiler. The code is very simple:

I'm trying to build a shared library in Cygwin using an i686-elf cross-compiler. The code is very simple:

int add(int a, int b) {
开发者_高级运维    return a + b;
}

void _init() {
    add(3, 4);
}

I'm compiling with the following command:

i686-elf-gcc -fPIC -shared -nostdlib core.c -o libcore.so

This should be producing a shared object, right? But GCC outputs a warning about not being able to find the _start symbol, which is the entry point for executables, not shared objects. Furthermore, readelf says the following:

$ readelf -a libcore.so
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
  ...
  Type:                              EXEC (Executable file)
  ...

What's going wrong here?


What's going wrong is essentially that you're targeting i686-elf, and nobody builds shared libraries for that target. -Wl,-shared will give you something which is marked as a shared library, but how exactly do you plan to load a shared library on a bare-metal target?


I believe that -shared on bare metal targets is a no-op (making the compiler believe the option wasn't specified) and therefore the compiler builds an executable. From info gcc on the command line:

'-shared'
    Produce a shared object which can then be linked with other
    objects to form an executable.  Not all systems support this
    option.  For predictable results, you must also specify the same
    set of options that were used to generate code ('-fpic', '-fPIC',
    or model suboptions) when you specify this option.(1)

... and scrolling down for footnotes:

  (1) On some systems, 'gcc -shared' needs to build supplementary stub
  code for constructors to work.  On multi-libbed systems, 'gcc -shared'
  must select the correct support libraries to link against.  Failing to
  supply the correct flags may lead to subtle defects.  Supplying them in
  cases where they are not necessary is innocuous.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号