gpt4 book ai didi

c++ - 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见

转载 作者:行者123 更新时间:2023-12-01 15:13:42 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What is an undefined reference/unresolved external symbol error and how do I fix it?

(37 个回答)


2年前关闭。




使用 C++14,我试图在存储常用变量的命名空间中定义一个变量(App::Common)。 main 函数应该是设置它的函数,因为它被设置为 argv[0]。同时,我需要所有其他类/文件都可以看到该变量。但我得到如下所示的链接器错误。另外,理想情况下,我希望变量是 const ,只有主函数会设置一次。

常见的.hpp

#pragma once
#include <string>
namespace App{
namespace Common{
extern std::string appPath;
}
}

主文件
#include "common.hpp"
#include "client.hpp"
#include <string>
int main() {
App::Common::appPath = argv[0];
}

客户端.hpp
#include "common.hpp"
class Client {
public:
void printAppPath();
};

客户端.cpp
#include <iostream>
#include <string>
#include "common.hpp"
#include "client.hpp"
void Client::printAppPath() {
std::cout << App::Common::appPath << std::endl;
}

链接器出现以下错误:
ld: main.o: in function `main':
main.cpp:(.text.startup.main+0x25): undefined reference to `App::Common::appPath[abi:cxx11]'
ld: Client.o: in function `Client::printAppPath()':
Client.cpp:(.text...): undefined reference to `App::Common::appPath[abi:cxx11]'

最佳答案


#pragma once
#include <string>
namespace App{
namespace Common{
extern std::string appPath;
}
}

仅包含变量 appPath 的声明没有它的定义。

这里
#include "common.hpp"
#include "client.hpp"
#include <string>
int main() {
App::Common::appPath = argv[0];
}

使用赋值运算符为变量 appPath 赋值好像它已经被定义了一样。然而实际上它的定义还不存在。

您可以在命名空间 Common 的任何封闭命名空间或命名空间内部的任何模块中定义变量。例如,您可以在 client.cpp 中定义它,例如
std::string App::Common::appPth;

关于c++ - 在命名空间中声明变量,在 main 中定义它,使其对所有其他文件可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59498343/

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