我正在尝试使用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)
...
这里出了什么问题?
问题本质上
是你的目标是 i686-elf,没有人为该目标构建共享库。 -Wl,-shared
会给你一些标记为共享库的东西,但是你打算如何在裸机目标上加载共享库呢?
我相信裸
机目标上的-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.