全局对象不能访问其他源文件C ++ [英] Global Object not accessible to other source files C++

查看:135
本文介绍了全局对象不能访问其他源文件C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ErrorLog 类,用于写入和修改日志文件。我想在主要事件之前和之后写入它来进行调试,我只想为整个应用程序使用 ErrorLog 类的一个实例。我试图通过放置

  ErrorLog exe_log;  声明一个 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 the ErrorLog class for the entire application. I tried declaring an ErrorLog object as a global by placing

ErrorLog 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆