static fstream
複数のソース ファイルでa を使用する必要があります。ただし、単一のファイルからのみ使用でき、他のファイルからは使用できません。さらに、他のファイルで使用してもエラーは発生せず、何もしません。
これはコードです:
/// 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