多个.cpp文件之间的fstream文件共享 [英] fstream file sharing among multiple .cpp files
问题描述
我在header.h下声明了一个静态fstream文件
static ofstream myfile_logs(D:\\\ \\ Elec ...);
main.cpp
Hi ,
I have declared one static fstream file under header.h
static ofstream myfile_logs("D:\\Elec...");
main.cpp
#include "header.h"
int main(...)
{
cal_mem();
verify_data();
}
verify_data()
{
myfile_logs << "verify...";
...
}
//end of main .cpp
commonFunc.cpp
#include "header.h"
void cal_mem()
{
myfile_logs << "calculate Mem";
...
..
}
//end of cal_mem
当我运行这个程序时,打开日志文件
i只获得
计算Mem文本显示
控件确实来到verify_data但文件没有附加或更新验证..文本
日志文件似乎只适用于commonFunc.cpp
如何为多个cpps附加此日志文件?
非常紧急修复此问题< br $> b $ b
谢谢
Anna
When i run this program, on opening the log file
i get only
"calculate Mem" text displayed
the control does come to verify_data but the file is not appended or updated with verify.. text
The log file seems to work only for commonFunc.cpp
how to have this log file appended for multiple cpps?
Quite urgent to fix this
Thanks
Anna
推荐答案
一种可能的解决方案:):
A possible solution :) :
// header.h
class logger
{
public:
static ofstream& GetStream()
{
static ofstream myfile_logs("D:\\Elec...");
return myfile_logs;
}
};
// any.cpp
void test()
{
logger::GetStream() << "test\n";
}
... else - 你也可以使用外部声明,而不是标题中的静态声明: )
...else - you can also use "external" declarations, instead of a static in the header :)
C和C ++中的关键字static(在其他情况下)具有文件本地的含义。因此,将这样的声明放在头文件中并不是一个好主意。这只会创建多个独立的对象,每个对象包含一个标题。
相反,您应该在main.cpp中定义流(或任何其他你的cpp文件)并将指针或引用传递给其他文件。
正如Eugen已经指出的那样,你可以在头文件中放一个extern声明要做到这一点。
The keyword static in C and C++ has (within others) the meaning of being file local. Hence, it is not a good idea to put such a declaration in a header file. That would just create multiple independent objects, one for each file into which you include the header.
Instead, you should define the stream in your main.cpp (or any other of your cpp files) and pass a pointer or reference around to the other files.
As Eugen already pointed out, you could put an extern declaration in the header file to accomplish that.
// in header.h
extern std::ofstream myfile_logs;
// this just declares a global variable, the definition of which
// resides in .cpp
// in main.cpp
std::ofstream myfile_logs ("D:\\Elec...");
// this defines a global variable shared among all your .cpp files
应该可以正常工作。
should just work fine.
这篇关于多个.cpp文件之间的fstream文件共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!