[英]Undefined Reference/ Multiple Definition for namespace extern variable , c++ structuring issue
我正在創建一個名稱空間來幫助我調試一個程序,但是我在弄清楚如何構建所有內容並讓它構建沒有問題時遇到了問題。
這是我當前的標題:
#ifndef HELPER_H
#define HELPER_H
#include <string>
#include <fstream>
#include <sstream>
namespace Helper
{
enum LOG { ONSCREEN, OFFSCREEN };
extern std::ofstream logfile;
//std::ofstream logfile("log.txt", std::ios_base::out | std::ios_base::app );
void EnableLogging();
void Log(std::string s, LOG type);
template <class T>
std::string ToString(const T& t)
{
std::ostringstream sstr;
sstr << t;
return sstr.str();
}
}
#endif // HELPER_H
這是Helper cpp文件:
#include "Helper.h"
#include <cstdio>
void Helper::EnableLogging()
{
#ifdef WIN32
// To use console on pc
std::ofstream ctt("CON");
freopen("CON", "w", stdout);
freopen("CON", "w", stderr);
#endif
#ifdef GP2X
//To log to text file on the caanoo
logfile.open("log.txt", std::ios_base::out | std::ios_base::app );
#endif
}
void Helper::Log(std::string s, LOG type)
{
if(type == OFFSCREEN)
{
#ifdef GP2X
//log << "L" << __LINE__ << "|T" << SDL_GetTicks() << "| " << s << std::endl;
logfile << s << std::endl;
#endif
#ifdef WIN32
printf("%s",s.c_str());
#endif
}
}
目前我得到一個未定義的Helper :: logfile錯誤引用 ,我完全理解這是因為我使用了extern關鍵字。
如果沒有extern關鍵字,我會得到一個不同的錯誤: Helper :: logfile的多重定義 。 該錯誤報告為另一個源文件中的“first defined ..”我試圖include "Helper.h"
。報告錯誤的行號是所述源文件中的構造函數但我懷疑沒有做任何事。
我確定我正在編譯幫助代碼錯誤的編譯但我無法弄清楚我應該怎么做呢?
您需要像標題一樣在標頭中聲明變量,以便在需要的地方使名稱可用。
// Helper.h
extern std::ofstream logfile;
您需要在源文件中定義它; 單一定義規則要求您只有一個定義。
// Helper.cpp
std::ofstream Helper::logfile("log.txt", std::ios_base::out | std::ios_base::app );
沒有定義,變量不存在,因此“未定義的引用”錯誤。
通過標題中的定義,它在包含標題的每個翻譯單元中定義,因此出現“多重定義”錯誤。
在一個源文件中定義,它定義一次,鏈接器很高興。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.