全局对象不能访问其他源文件C ++ [英] Global Object not accessible to other source files C++
问题描述
我有一个 ErrorLog
类,用于写入和修改日志文件。我想在主要事件之前和之后写入它来进行调试,我只想为整个应用程序使用 ErrorLog
类的一个实例。我试图通过放置
ErrorLog exe_log;
$ p>声明一个ErrorLog
$ p>到头文件中,所以它是可访问其他文件,但我不断收到一个错误,说它已经定义。是否有正确的方法来定义全局对象?解决方案您需要一个头文件中的和源文件中的定义。
foo.h:
extern ErrorLog exe_log; //声明(注意extern)$ b $ b
foo.cpp:
ErrorLog exe_log; // definition
bar.cpp:
#includefoo.h
I have an
ErrorLog
class, that is used to write and modify log files. I'd like to write to it before and after major events for debugging purposes and I only want to use one instance of theErrorLog
class for the entire application. I tried declaring anErrorLog
object as a global by placingErrorLog exe_log;
into a header file so it is accessbile to other files, but I keep getting an error saying it is already defined. Is there a correct way to defing global objects?
解决方案You need a declaration in a header file and a definition in a source file.
foo.h:
extern ErrorLog exe_log; // declaration (note the "extern")
foo.cpp:
ErrorLog exe_log; // definition
bar.cpp:
#include "foo.h"
这篇关于全局对象不能访问其他源文件C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!