[英]the result of linking two strong function symbol with the same function signature use g++ and why?
I am confused about the linking procedure when linking two same function symbol. 当链接两个相同的功能符号时,我对链接过程感到困惑。
point.h: point.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
point.cpp: point.cpp:
#include "point.h"
void * get_y(struct Point &pt)
{
int a = 1;
return &(pt.p.y);
}
test.cpp: test.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;
}
I get two objects by 我得到两个物体
g++ -o double_point -DDOUBLE_POINT -c point.cpp
g++ -o int_point -c point.cpp
and let use g++ to link them together with test.cpp 并使用g ++将它们与test.cpp链接在一起
My question is: 我的问题是:
why I can link them successfully, I mean there are 2 same symbol, why ld doesn't get error 为什么我可以成功链接它们,我的意思是有两个相同的符号,为什么ld不会出错
I think if I use weak symbol on one of the functions, the linking result will always be the strong function symbol, but the result doesn't change, it always be the symbol that come first, I want to know why 我想如果在其中一个函数上使用弱符号,则链接结果将始终是强函数符号,但结果不会改变,它始终是最先出现的符号,我想知道为什么
my compiler: 我的编译器:
GNU C++ version 3.4.5 20051201 (Red Hat 3.4.5-2) (x86_64-redhat-linux) compiled by GNU C version 3.4.5 20051201 (Red Hat 3.4.5-2). 由GNU C版本3.4.5 20051201(Red Hat 3.4.5-2)编译的GNU C ++版本3.4.5 20051201(Red Hat 3.4.5-2)(x86_64-redhat-linux)。
GNU assembler version 2.15.92.0.2 (x86_64-redhat-linux) using BFD version 2.15.92.0.2 20040927 使用BFD版本2.15.92.0.2 20040927的GNU汇编程序版本2.15.92.0.2(x86_64-redhat-linux)
Have a look to the following links : 看一下以下链接:
C++: Different classes with the same name in different translation units C ++:在不同的翻译单元中具有相同名称的不同类
http://en.wikipedia.org/wiki/One_Definition_Rule http://en.wikipedia.org/wiki/One_Definition_Rule
You are violating the One Definition Rule, and thus causing undefined behavior. 您违反了一个定义规则,从而导致未定义的行为。 While I understand what you might be wanting to do, the fact is that your code is wrong and the compiler toolchain does not need to provide any specific behavior.
虽然我了解您可能要执行的操作,但事实是您的代码是错误的,并且编译器工具链不需要提供任何特定的行为。
What is the real problem you want to solve? 您要解决的真正问题是什么? Because this is clearly not the way to the solution.
因为这显然不是解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.