Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么共享库中的_属性_((构造函数))不起作用?_C_Linux_Clang_Shared Libraries - Fatal编程技术网

C 为什么共享库中的_属性_((构造函数))不起作用?

C 为什么共享库中的_属性_((构造函数))不起作用?,c,linux,clang,shared-libraries,C,Linux,Clang,Shared Libraries,我在ctor.c中有以下代码: #include<stdio.h> static void __attribute__((constructor)) ctor() { printf("HAHA"); } 然后我跑: LD_PRELOAD=shared.so echo Hallo 它打印 Hallo 我希望看到: HAHAHallo 为什么这不起作用 有关二进制文件的一些信息: > objdump -s -j .init_array shared.so

我在ctor.c中有以下代码:

#include<stdio.h>

static void __attribute__((constructor)) ctor() {
        printf("HAHA");
}
然后我跑:

LD_PRELOAD=shared.so echo Hallo
它打印

Hallo
我希望看到:

HAHAHallo
为什么这不起作用

有关二进制文件的一些信息:

> objdump -s -j .init_array shared.so

shared.so:     file format elf64-x86-64

Contents of section .init_array:
 200798 b0060000 00000000 e0060000 00000000  ................

> nm shared.so
00000000002007b8 d _DYNAMIC
00000000002009b0 d _GLOBAL_OFFSET_TABLE_
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable
                 w _Jv_RegisterClasses
0000000000000790 r __FRAME_END__
00000000002007b0 d __JCR_END__
00000000002007b0 d __JCR_LIST__
00000000002009e8 d __TMC_END__
00000000002009e8 B __bss_start
                 w __cxa_finalize@@GLIBC_2.2.5
0000000000000670 t __do_global_dtors_aux
00000000002007a8 t __do_global_dtors_aux_fini_array_entry
00000000002009e0 d __dso_handle
0000000000200798 t __frame_dummy_init_array_entry
                 w __gmon_start__
00000000002009e8 D _edata
00000000002009f0 B _end
0000000000000700 T _fini
0000000000000578 T _init
00000000002009e8 b completed.6661
00000000000006e0 t ctor
00000000000005e0 t deregister_tm_clones
00000000000006b0 t frame_dummy
                 U printf@@GLIBC_2.2.5
0000000000000620 t register_tm_clones
这表明:

(a) 存在ctor函数。它不会被链接器删除,就像一些有类似问题的人一样

(b) .init_数组在我看来没问题。有两个条目(而不是一个),它们指向frame_dummy和ctor。(我用了这个答案:)

(c) 通过一步编译和链接解决了这个问题,我已经在做了


PS:当我使用gcc编译时,它也不起作用

我对c++构造函数也有类似的问题

struct Foo {
    Foo() {
        printf("foo");
    }
} foo;
这应该在调用main()之前打印“foo”,但它没有。但我在我的项目中有非常相似的东西,效果很好

我发现,如果源文件中没有其他从外部调用的内容,则不会调用构造函数


尝试从外部调用伪函数。

有两个错误:

(a) LD_预加载需要一个绝对路径


(b) “echo”是shell内置的,因此不会启动二进制文件,因此不会预加载任何内容。通过我自己的“hello world”程序,它可以工作

如果我使用第二个源文件和一个主函数并链接到一个可执行文件,它就可以工作。作为共享库链接不起作用。我认为您的问题是链接器不能访问对象文件,因此如果文件中没有任何内容被使用,就会错过构造函数。对我来说,nm表示构造函数是二进制的。甚至.init_数组似乎也已正确填充。请参阅
struct Foo {
    Foo() {
        printf("foo");
    }
} foo;