0

链接两个相同的功能符号时,我对链接过程感到困惑。

点.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: %lf\nint: %d\n", *(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) 编译。

使用 BFD 版本 2.15.92.0.2 的 GNU 汇编器版本 2.15.92.0.2 (x86_64-redhat-linux) 20040927

4

2 回答 2

0

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

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

于 2013-10-08T12:40:52.787 回答
0

Have a look to the following links :

C++: Different classes with the same name in different translation units

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

于 2013-10-08T12:35:53.060 回答