gpt4 book ai didi

c++ - C++中的命名空间如何链接?

转载 作者:行者123 更新时间:2023-11-28 06:19:08 25 4
gpt4 key购买 nike

我的代码结构如下:

文件1.cpp

namespace file1
{
...
...
}
int main()
{
file2::func();
}

文件2.cpp

namespace file2
{
...
...
}

如何将 file1.cpp 与 file2.cpp 链接起来?它抛出 file1.cpp 找不到 file2 命名空间 的错误。我尝试在 file1.cpp 中添加 namespace file2{},但仍然出现同样的错误。

最佳答案

您需要一个 header 来声明要从多个源文件访问的内容:

// file2.h
#pragma once // or a traditional include guard if you prefer

namespace file2 {
void func();
}

现在从 file1.cpp 中包含它,以便从那里启用 file2::func

// file1.cpp
#include "file1.h"

// ...

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com