当我想要一个共享库时,GCC输出一个可执行的ELF文件

时间:2011-05-07 04:25:31

标签: c gcc shared-libraries cross-compiling elf

我正在尝试使用i686-elf交叉编译器在Cygwin中构建一个共享库。代码非常简单:

int add(int a, int b) {
    return a + b;
}

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

我正在使用以下命令进行编译:

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

这应该是一个共享对象,对吧?但GCC会输出一个警告,指出无法找到_start符号,这是可执行文件的入口点,而不是共享对象。此外,readelf说明如下:

$ 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)
  ...

这里出了什么问题?

2 个答案:

答案 0 :(得分:2)

出现问题的主要原因在于您的目标是i686-elf,而且没有人为该目标构建共享库。 -Wl,-shared会为您提供标记为共享库的内容,但您打算如何在裸机目标上加载共享库?

答案 1 :(得分:0)

我认为裸机目标上的-shared是无操作的(使编译器认为没有指定选项),因此编译器构建了一个可执行文件。从命令行上的info gcc开始:

'-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)

...向下滚动脚注:

  (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.