链接两个具有相同函数签名的强函数符号的结果使用 G++ 以及原因
the result of linking two strong function symbol with the same function signature use g++ and why?
我对链接两个相同函数符号时的链接过程感到困惑。
点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.520051201 (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
您违反了一个定义规则,从而导致未定义的行为。虽然我理解您可能想要做什么,但事实是您的代码是错误的,编译器工具链不需要提供任何特定行为。
您想解决的真正问题是什么?因为这显然不是解决问题的方法。
相关文章:
- 如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?
- 分段错误分配函数结果
- 使用函数结果作为参数的 C++
- 从可调用可变参数元组中的函数结果创建元组
- 将多个向量(函数结果)组合到一个使用模板中
- 是否可以使用自动占位符来推断非类型模板参数中的函数结果
- 大小由虚函数结果决定的数组
- C/C++编译器是否会通过重用最近计算的函数结果来优化代码?
- 从函数结果中分配 std::shared_ptr 的一行是什么?
- 将函数结果分配给变量的问题
- std::具有自定义比较函数结果的排序函数错误:必须调用对非静态成员函数的引用
- C++SFINAE运算符/函数结果类型检查
- 将函数结果作为"output parameter"返回是什么意思?
- 这将是在将函数分配给变量或一次又一次地调用函数之间使用函数结果的最佳方式
- C++中的绑定函数结果
- 有没有比生成/累积更快的方法来计算函数结果的平均值
- 为什么当递归函数结果相乘时,g++ 仍然优化尾递归
- C++成员函数结果缓存实现
- 用于输出列中对数函数结果的合适循环(c++)
- 将记录作为函数结果从Delphi DLL传递到c++