尝试创建流的错误日志 - 获取"one or more multiply defined symbols found"

Trying to create an error log ofstream -- getting "one or more multiply defined symbols found"

本文关键字:or one more defined found symbols multiply 获取 创建 错误 日志      更新时间:2023-10-16

我正在尝试这样做:

#pragma once
#include <fstream>
#include <string>
static std::ofstream ErrorLog;
void InitErrorLog(std::string FileName) {
    ErrorLog.open(FileName);
}

但是在多个 CPP 文件中 #include 时收到"找到一个或多个乘法定义的符号"错误。STL 在做什么(提供 cout、cin、cerr 等——这种方法起源于重定向 cerr 的替代方案)而我不是?

您将在头文件中提供ErrorLog的定义。相反,在源文件中定义它,并在标头中保留一个 extern 声明

std::ofstream ErrorLog;
void InitErrorLog(std::string FileName) {
    ErrorLog.open(FileName);
}

页眉

extern std::ofstream ErrorLog;
void InitErrorLog(std::string FileName);

此外,为了将函数保持在标头处,您必须使其inline

你打破了一个定义规则。您需要使该方法inline .

inline void InitErrorLog(std::string FileName) {
    ErrorLog.open(FileName);
}

另外,请注意,通过声明变量 static ,您将拥有每个翻译单元的副本 - 即它不是全局的。要使其全局化,您需要在标头中extern声明它,并在单个实现文件中定义它。