使用 Clang++ 有没有办法将文件作为命名空间等包含在内?

With Clang++ is there a way to include a file as namespace, etc.?

有没有办法在不改变要包含的文件的情况下命名空间(或其他方式)包含文件?

比如:

#include "A.cpp" as namespace A

据此,例如:

Start.cpp

// #include "A.cpp" as namespace A
#include "B.cpp"

int main() {
    // Could call A::Function() 
    // or similar??
}

A.cpp

int Function() {
    return 1;
}

B.cpp

int Function() {
    return 2;
}

编译:

clang++ --std=c++2a Start.cpp -o Start.o; ./Start.o

C++ 中没有这样的功能。你能做的最好的是:

namespace A {
#include "A.cpp"
}

#include 只是粘贴文件,因此这可能会给您带来一些错误。

好的 C++ 库定义了它们自己的命名空间。

希望 C++20 中的模块能够简化这个!

您可以将 include 包装到命名空间中。

namespace A {
#include "A.cpp"
}

但是,您面临的风险是该文件中包含的所有内容也是该新命名空间的一部分,并且最终可能会出现不同的问题,例如未解析的符号。

注意:您不应包含 cpp 文件。这样不好。