sách gpt4 ăn đã đi

c++ - C++ 命名空间内的外部 "C"链接?

In lại Tác giả: IT Lão Cao 更新时间:2023-10-28 22:03:33 26 4
mua khóa gpt4 giày nike

namespace someNameSpace {
extern "C" void doSomething()
{
someOperations();
}
}

我想在 C++ 和 C 环境中运行 làmCái gì đó()

如果我将 someNameSpace 暴露给 extern "C" 链接,它是否仍在封装 làmCái gì đó()?

有没有一种好方法可以在 C++ 和 C 之间共享函数,同时避免污染 C++ 端的全局命名空间?

biên tập:因为这段代码主要用于C++模式,而C链接仅供测试使用,我想这是一个更好的方法。

namespace someNameSpace {
#ifdef COMPILE_FOR_C_LINKAGE
extern "C"
#khác
extern "C++"
#kết thúc nếu
{
void doSomething()
{
someOperations();
}
}
}

câu trả lời hay nhất

您的代码有效,但您应该注意所有具有 extern "C" 链接的函数共享相同的 namespace ,但不要与 C++ 的“ namespace ”概念混淆: 你的函数确实是 someNameSpace::doSomething,但你不能在任何其他命名空间中拥有任何其他具有非限定名称 doSomething của extern "C" 函数.

参见 7.5/6:

At most one function with a particular name can have C language linkage. Two declarations for a function with C language linkage with the same function name (ignoring the namespace names that qualify it) that appear in different namespace scopes refer to the same function. Two declarations for a variable with C language linkage with the same name (ignoring the namespace names that qualify it) that appear in different namespace scopes refer to the same variable. An entity with C language linkage shall not be declared with the same name as a variable in global scope, unless both declarations denote the same entity; no diagnostic is required if the declarations appear in different translation units. A variable with C language linkage shall not be declared with the same name as a function with C language linkage (ignoring the namespace names that qualify the respective names); no diagnostic is required if the declarations appear in different translation units. [Note: Only one definition for an entity with a given name with C language linkage may appear in the program (see 3.2); this implies that such an entity must not be defined in more than one namespace scope. — end note]

贵公司或项目的全局风格仲裁员应该能够就适合您的代码库的命名策略向您提供建议。

关于c++ - C++ 命名空间内的外部 "C"链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28996944/

26 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress