C++ 错误:‘;logFileObj’;不命名类型

C++ 错误:‘;logFileObj’;不命名类型,c++,compilation,compiler-errors,g++,C++,Compilation,Compiler Errors,G++,我有一个名为global.h的文件,其内容如下: #define DEPTH 10 #define LOGGING //to log the progress of the program. #ifdef LOGGING #include <fstream> #include <string> extern std::string logFileName; extern std::ofstream logFileObj; #endif 我在编译过程中经常遇到以下

我有一个名为
global.h
的文件,其内容如下:

#define DEPTH 10
#define LOGGING     //to log the progress of the program.
#ifdef LOGGING
#include <fstream>
#include <string>
extern std::string logFileName;
extern std::ofstream logFileObj;
#endif
我在编译过程中经常遇到以下错误:

src/main.cpp:13:1: error: ‘logFileObj’ does not name a type
src/main.cpp:14:1: error: ‘logFileObj’ does not name a type

感谢您的帮助。

C++不允许在功能之外进行操作。C++允许你在全局范围内定义变量,但是你需要在函数内部进行操作。 如果我没有看错您的问题,您只需要一个函数,并在需要时调用它:

#include <fstream>
#include <utility>
#include <string>

template<typename T>
void WriteLog(const std::string& log_file_name, const std::string& prefix, const T& data)
{
  std::ofstream log_file_handler(log_file_name.c_str(), std::ios::app);  // if you use C++11, you could use string directly
   log_file_handler << prefix << data << std::endl;
}
#包括
#包括
#包括
模板
void WriteLog(const std::string和log\u file\u name,const std::string和prefix,const T和data)
{
std::ofstream log_file_handler(log_file_name.c_str(),std::ios::app);//如果使用c++11,可以直接使用字符串

log_file_handler是函数中的
logFileObj.open(logFile);
。@billz我弄错了。它不在函数中。据我所知,main应该是第一个被调用的函数,这就是这里的错误。我对吗。
#include <fstream>
#include <utility>
#include <string>

template<typename T>
void WriteLog(const std::string& log_file_name, const std::string& prefix, const T& data)
{
  std::ofstream log_file_handler(log_file_name.c_str(), std::ios::app);  // if you use C++11, you could use string directly
   log_file_handler << prefix << data << std::endl;
}
WriteLog<int>("app.log", "depth:", DEPTH);