gpt4 book ai didi

C++ LNK2001 尝试使用外部变量时出错

转载 作者:行者123 更新时间:2023-12-04 17:01:10 25 4
gpt4 key购买 nike

我正在尝试创建一个实用程序类,我可以在我的程序中使用它,例如日志记录、调试等。
在 Java 中,我知道我可以通过声明变量和函数来实现 静态 ,当我阅读更多如何在 C++ 中做到这一点时,我应该使用 外部 , 被命名空间包围,不要填充太多文件。
在尝试初始化那些 时外部 变量,在构造函数类中,
我收到以下错误:

application.cpp.obj : error LNK2001: unresolved external symbol "classApplication * Lib::app"

application.cpp.obj : error LNK2001: unresolved external symbol "classGraphics * Lib::graphics"


这对我来说没什么意思,但存在链接问题?
我有以下2个文件:
// lib.h
#ifndef LIB_H
#define LIB_H

#include "graphics.h"
#include "application.h"

namespace Lib {
extern Application *app;
extern Graphics *graphics;
}

#endif //LIB_H


// application.cpp
#include "include/application.h"
#include "include/lib.h"
.
Application::Application(Listener* listener, Configuration* config, Graphics* graphics) {
.
.
// Our library for graphics
this->graphics = graphics;
.
.
// creating the environment utils
Lib::app = this;
Lib::graphics = graphics;
.
.
}

最佳答案

extern意味着你在别处定义你的变量。在您的情况下,您必须在 lib.cpp 中包含以下内容:

namespace Lib {
Application *app;
Graphics *graphics;
}
也就是说,你的设计是有问题的:

In Java, I know I can make it as by declaring the variables andfunctions static


你可以在 C++ 中做同样的事情,在这种情况下它会更有意义。

关于C++ LNK2001 尝试使用外部变量时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65350310/

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