gpt4 book ai didi

外部声明的全局对象的 C++ 链接器错误

转载 作者:行者123 更新时间:2023-12-04 16:52:37 24 4
gpt4 key购买 nike

我在使用 extern 时遇到问题- 声明的全局对象。据我了解,我应该能够将对象声明为 extern在头文件中,在源文件中定义它,然后在包含头文件的任何其他源文件中使用该对象。但是,使用以下结构时,我收到链接器错误,提示 logger符号未定义。
记录器.hpp:

#ifndef MY_LOGGER_H
#define MY_LOGGER_H

namespace foo {
class Logger {
public:
void log(int num);
};

extern Logger logger;
} // foo

#endif
记录器.cpp:
#include "logger.hpp"
using namespace foo;

void Logger::log(int num) { /* Do stuff */ }

Logger logger;
主.cpp:
#include "logger.hpp"
using namespace foo;

int main() {
logger.log(3); // arbitrary number
}
如果我声明 Loggermain() ,一切正常,所以头文件和源文件被正确包含和链接。
我使用内置类型(例如 int )遇到相同的错误,所以我认为这不是 Logger 的问题类本身。
如果这是一个愚蠢的问题,我有几年的 C++ 经验,但直到现在我都避免使用像瘟疫这样的全局变量。

最佳答案

本声明

Logger logger;
在全局命名空间中定义一个变量。
您需要使用限定名称编写
#include "logger.hpp"

using namespace foo;

void Logger::log(int num) { /* Do stuff */ }

Logger foo::logger;
来自 C++ 20 标准(9.8.1.2 命名空间成员定义)

2 Members of a named namespace can also be defined outside thatnamespace by explicit qualification (6.5.3.2) of the name beingdefined, provided that the entity being defined was already declaredin the namespace and the definition appears after the point ofdeclaration in a namespace that encloses the declaration’s namespace


这是一个演示程序。
#include <iostream>

namespace foo {
class Logger {
public:
void log(int num);
};

extern Logger logger;
} // foo

using namespace foo;

void Logger::log(int num) { /* Do stuff */ }

Logger foo::logger;

int main()
{
logger.log(3);

return 0;
}

关于外部声明的全局对象的 C++ 链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69268747/

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