链接两个具有相同函数签名的强函数符号的结果使用 G++ 以及原因

the result of linking two strong function symbol with the same function signature use g++ and why?

本文关键字:函数 结果 符号 G++ 两个 链接      更新时间:2023-10-16

我对链接两个相同函数符号时的链接过程感到困惑。

点H:

#ifndef _POINT_H_
#define _POINT_H_
struct dpoint_t
{
    /* data */
    double x, y;
};
struct ipoint_t
{
    /* data */
    int x, y;
};
#ifdef DOUBLE_POINT
    typedef struct dpoint_t data;
#else
    typedef struct ipoint_t data;
#endif
struct Point
{
    data p;
    int idx;
};
/*
#ifndef DOUBLE_POINT
__attribute__ ((weak)) 
#endif
*/
void * get_y(struct Point &x);
#endif

点.cpp:

#include "point.h"

void * get_y(struct Point &pt)
{
    int a = 1;
    return &(pt.p.y);
}

测试.cpp:

#include <stdio.h>
#include "point.h"
int main()
{
    struct Point x;
    x.p.x = 10.0;
    x.p.y = 5.0;
    void *p = get_y(x);
    printf("double: %lfnint: %dn", *(double *)p, *(int *)p);
    return 0;
}

我得到两个对象

g++ -o double_point -DDOUBLE_POINT -c point.cpp
g++ -o int_point -c point.cpp

让我们使用 G++ 将它们与 test 链接在一起.cpp

我的问题是:

为什么

我可以成功链接它们,我的意思是有 2 个相同的符号,为什么 ld 没有错误

我认为如果我在其中一个函数上使用弱符号,链接结果将始终是强函数符号,但结果不会改变,它始终是第一个出现的符号,我想知道为什么

我的编译器:

GNU C++ 版本 3.4.5

20051201 (Red Hat 3.4.5-2( (x86_64-redhat-linux( 由 GNU C 版本 3.4.5 20051201 (Red Hat 3.4.5-2( 编译。

GNU 汇编程序版本 2.15.92.0.2

(x86_64-redhat-linux( 使用 BFD 版本 2.15.92.0.2 20040927

请查看以下链接:

C++:不同翻译单元中具有相同名称的不同类

http://en.wikipedia.org/wiki/One_Definition_Rule

您违反了一个定义规则,从而导致未定义的行为。虽然我理解您可能想要做什么,但事实是您的代码是错误的,编译器工具链不需要提供任何特定行为。

您想解决的真正问题是什么?因为这显然不是解决问题的方法。