为什么__attribute __((constructor))在静态库中不起作用? [英] Why doesn't __attribute__((constructor)) work in a static library?

查看:584
本文介绍了为什么__attribute __((constructor))在静态库中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,程序应打印"foo named":

In the following example, the program should print "foo called":

// foo.c
#include <stdio.h>

__attribute__((constructor)) void foo()
{
    printf("foo called\n");
}

// main.c
int main()
{
    return 0;
}

如果程序是这样编译的,它将起作用:

If the program is compiled like this, it works:

gcc -o test main.c foo.c

但是,如果将foo.c编译到静态库中,则程序不会打印任何内容.

However, if foo.c is compiled into a static library, the program prints nothing.

gcc -c main.c
gcc -c foo.c
as rcs foo.a foo.o
gcc -o test foo.a main.o

为什么会这样?

推荐答案

链接器在最终程序中不包含foo.a中的代码,因为main.o中没有引用它的代码.如果main.c重写如下,该程序将运行:

The linker does not include the code in foo.a in the final program because nothing in main.o references it. If main.c is rewritten as follows, the program will work:

//main.c

void foo();

int main()
{
    void (*f)() = foo;
    return 0;
}

此外,在使用静态库进行编译时,gcc(或链接程序)的参数顺序很重要:该库必须位于引用它的对象之后.

Also, when compiling with a static library, the order of the arguments to gcc (or the linker) is significant: the library must come after the objects that reference it.

gcc -o test main.o foo.a

这篇关于为什么__attribute __((constructor))在静态库中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆