English 中文(简体)
为什么焊接器允许使用相同方法的多类定义?
原标题:Why does the ld linker allow multiple class definitions with the same methods?

考虑此文件, first.cpp , 包含分类定义和使用 :

#include <iostream>

struct Foo
{
    Foo(){ std::cout << "Foo()" << std::endl; }
    ~Foo(){ std::cout << "~Foo()" << std::endl; }
};

int main(){
    Foo f;
    return 0;
}

和另一个, second.cpp ,含有相互冲突的类别定义:

#include <iostream>

struct Foo
{
    Foo();
    ~Foo();
};

Foo::~Foo(){ std::cout << "wrong ~Foo()" << std::endl; }

链接人抱怨重复符号, 因为有两个功能, 名称相同, 但是这些带有重复类方法的文件没有错误地编译 。

我编集了这些命令:

$ g++ -c second.cpp -o second
$ g++ second first.cpp -o first

将参数重新排序到第二个 g/code> 调用并不改变输出 。

first 运行时, 这就是输出 :

$ ./first
Foo()
wrong ~Foo()

< strong> 为什么链接允许重复类方法? 如果显然允许, 为什么 < code> wrongong ~Foo () 打印?

最佳回答

再一次, 未定义的行为。 您的程序对 < code> Foo 的毁灭器有多重定义, 这意味着它违反了网上解决。 此程序是错误的, 任何事情都可能发生 。

为何链接器不接收它? 当一个函数在分类定义中被定义时, 它会隐含到 < code> inline 。 汇编者通常将这些函数标记为弱符号。 链接者然后获得所有翻译单位并尝试解析符号。 如果需要, 弱符号会被链接者丢弃( 也就是说, 如果符号已经在别处定义了 ) 。

至于程序的实际输出,它看起来像编译器实际上没有将呼叫内嵌到构建器上,因此在运行时发送到链接器(非微弱的)留下的符号上。


为什么连线器允许使用重复的方法?

因为所有符号(但最多一个)都是弱符号(即 inline )

为何印错了 ~Foo ()?

因为电话没有内嵌, 链接器掉了弱符号

问题回答

暂无回答




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签