为什么包含守卫不会阻止多个函数定义? [英] Why include guards do not prevent multiple function definitions?

查看:112
本文介绍了为什么包含守卫不会阻止多个函数定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

链接器在此报告重复符号:

The linker reports duplicate symbol on this:

#ifndef testttt
#define testttt

void anything(){
    std::cout<<"hellooooooo";
}

#endif

因为它在include卫士,我希望这个函数只定义一次。但显然不是。

Because it is inside the include guards, I would expect that this function is only defined once. But apparently not.

我知道我可以把 static 放在它前面,然后它会工作我仍然发现讽刺,因为静态应该给它内部链接,但该函数可以使用从多个cpp文件)。

I know I can put the word static in front of it and then it will work (which I still find ironic, since static is supposed to give it internal linkage, yet the function can be used from multiple cpp files).

所以我想我的两部分问题是:1)为什么include保护不会阻止这个函数的多个定义,就像它们对其他头项一样,2)为什么 static 应该防止名称在其他翻译单位中的可见性?我添加它,我可以从包含这个头文件的任何地方调用这个函数。

So I guess my two-part question is: 1) Why do the include guards not prevent multiple definitions of this function like they do for other header items, and 2) Why does the static word resolve this when static is supposed to prevent names from visibility in other translation units? I add it, and I can actually call this function from anywhere that includes this header file.

推荐答案

为什么include保护不会阻止这个函数的多个定义,就像它们对其他头项

"1) Why do the include guards not prevent multiple definitions of this function like they do for other header items"

因为每个翻译单元分别处理和通过相同的条件。翻译单元不会共享其他翻译单元遇到的预处理器定义。这意味着 all 将处理该标题的翻译单元将包含该函数的定义。当然,链接器会抱怨同一个函数有多个定义。

Because each translation unit (i.e. .cpp file) is processed separately and goes through the same conditional. Translation units won't share the preprocessor definitions encountered by other translation units. This means that all the translation units that will process that header will include a definition for that function. Of course, the linker will then complain that the same function has multiple definitions.

2)为什么静态字解决这个问题static

因为 static 关键字使私人副本

但是,如果你希望在一个共享头中定义该函数,你应该将它标记为 inline ,这将解决您的问题,并将使预处理器保护不必要。

If you want that function to be defined in a shared header, however, you should rather mark it as inline, which will solve your problem and will make the preprocessor guards unnecessary.

这篇关于为什么包含守卫不会阻止多个函数定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆