我需要在多個源文件中使用static fstream
。但是我只能從一個文件中使用它,而不能從其他文件中使用它。此外,它在其他文件中的使用不會給出任何錯誤,它只是無所作爲。我只能從一個文件訪問靜態fstream
這是代碼:
/// log.h
#ifndef LOG_H
#define LOG_H
#include <fstream>
static std::ofstream ofs;
#define LOG(level) ofs << level << ": "
#endif
/// test.cpp
#include "log.h"
#include "other.h"
int main()
{
ofs.open("file.log");
LOG(5) << "Test log 1" << std::endl; // OK
OtherFunc();
}
/// other.h
#ifndef OTHER_H
#define OTHER_H
extern int OtherFunc();
#endif
/// other.cpp
#include "other.h"
#include "log.h"
int OtherFunc()
{
LOG(5) << "Test log 2" << std::endl; // Nothing
}
這是生成的文件:
5: Test log 1
謝謝!
平臺:
Linux的
G ++ 4.5.1
你應該考慮讓'LOG()'成爲一個普通的舊函數。將所需狀態(本例中的流)保留在函數實現的私有位置。這樣,您可以避免讓每個使用它的人都必須知道流。 –