简体   繁体   English

重新考虑在C ++中包含C头

[英]Inclusion of C headers in C++ revisited

I just read a question on SO discussing scenarios in which a piece of code is valid in both C and C++ but would produce different behavior in each language. 我刚刚阅读了一个关于SO讨论场景的问题 ,其中一段代码在C和C ++中都有效,但会在每种语言中产生不同的行为。

This begs the question: Could this ever be a problem when including C headers in C++ code? 这引出了一个问题: 在C ++代码中包含C头时,这可能是一个问题吗?

I know from this question that you should include C headers like this: 从这个问题中知道你应该包含这样的C头:

extern "C" {
#include <your_os_or_library_header_in_c.h>
}

But all I found so far is that the extern "C" only guarantees that name mangling is turned off. 但到目前为止我发现的只是extern“C”只能保证关闭名称

I couldn't find any information on whether it evaluates all statements as C, so that eg sizeof('a') or 10 //* comment */ 2 (which you could find in an inline function) are parsed as C and not C++. 我找不到关于它是否将所有语句评估为C的任何信息,因此例如sizeof('a')10 //* comment */ 2 (你可以在内联函数中找到)被解析为C而不是C ++。 (Note that relying on such behavior as someone who writes a C header is obviously a bad idea, but I'm asking it from a purely academic standpoint of "What if?".) (请注意,依赖于编写C头的人这样的行为显然是一个坏主意,但我从纯粹的学术角度问“如果会怎么样?”。)

Does the C++ standard say that enclosing a block of code in extern "C" means that all statements in it must be parsed as C? C ++标准是否说在extern "C"中包含一段代码意味着它中的所有语句必须被解析为C?

extern "C" is a C++ construct which affects language linkage in a C++ program. extern "C"是一个C ++结构,它影响C ++程序中的语言链接。 It does not switch the language to C in any way. 它不会以任何方式将语言切换为C. All source text inside an extern "C" declaration is still parsed as C++ and as C++ only. extern "C"声明中的所有源文本仍然被解析为C ++和C ++。

Note that extern "C" affects more than just name mangling - it is (theoretically) possible that functions with C and C++ language linkage could have different calling conventions, for example. 请注意, extern "C"不仅仅影响名称修改 - 例如,(理论上)C和C ++语言链接的函数可能具有不同的调用约定。

extern "C" only changes linking, ie mangling and possibly the calling convention. extern "C"只改变链接,即修改和可能的调用约定。 Try compiling and running this program with both a C and a C++ compiler: 尝试使用C和C ++编译器编译和运行此程序:

#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif
    inline void putsizeofchar()
    {
        printf("%zd\n", sizeof(char));
    }
#ifdef __cplusplus
}
#endif

int main()
{
    putsizeofchar();
    return 0;
}

Since header inclusion is textual substitution in both languages, the lack of a header doesn't make any difference. 由于标题包含是两种语言的文本替换,因此缺少标题不会有任何区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM