当函数指针被分配给另一个文件中具有相同名称的函数时,核心转储

Core dumped when a function pointer is assigned with a funtion that has the same name in another file

我只是将我的问题抽象为以下场景: 三个files:a.h,a.c,b.c,代码如下:

a.c

#include "a.h"
#include <stdio.h>

int (*call2)();

int call1(int (*cb)()){
    call2=cb;
    printf("success!");
    return 1;
}

a.h

int call1();

b.c

#include <stdio.h>
#include "a.h"

int call2(){return 0;};

int main(){
    call1(call2);
}

然后用 gcc a.c b.c -o b 编译这些文件只会得到一些警告:

/usr/bin/ld: Warning: alignment 1 of symbol `call2' in /tmp/cc0wbcYh.o is smaller than 8 in /tmp/ccuDjeEs.o
/usr/bin/ld: Warning: size of symbol `call2' changed from 8 in /tmp/ccuDjeEs.o to 11 in /tmp/cc0wbcYh.o
/usr/bin/ld: Warning: type of symbol `call2' changed from 1 to 2 in /tmp/cc0wbcYh.o

然后 运行 它与 './b' 将得到

Segmentation fault (core dumped)

我的想法: 显然,行 call2=cb; 导致了这个 corrupt.That 意味着,将函数分配给具有相同名称的函数指针是错误的 operation.I 认为原因与 gcc 编译器如何存储一个函数指针和一个 function.But 我不熟悉 gcc 编译器的实现。 谁能帮帮我?

通过将和 call2 定义为具有两种不同类型的两个不同对象,您违反了一个定义规则。行为未定义。

要实现您想要的行为,请同时声明 call2static,以便它们具有内部链接并且不会相互冲突。