【问题标题】:Variable already defined in .obj, but no circular includes [duplicate]已在 .obj 中定义的变量,但没有循环包含 [重复]
【发布时间】:2015-05-05 17:23:03
【问题描述】:

我知道,SO 上已经有很多类似的问题和解决方案,我阅读了它们,但没有一个能帮助我解决我的问题。

我创建了一个日志类。 这里是Logger.h

#ifndef LOGGER_H
#define LOGGER_H

namespace Logger
{
namespace debug
{

    int Error = 0, OtherNumber;

    class log
    {
    public:     // Methods
        void Save();

    private:    // Members
        static int indentation;
        const std::wstring context;
        int Type, LineNumber;

    public:     // Constructor, Destructor
        log( const std::wstring& context, int LineNumber, int Type );
        ~log();

    };//class log

}//namespace debug

}//namespace Logger

#endif //LOGGER_H

Logger.cpp

#include "stdafx.h"

#include "Logger.h"

namespace Logger
{
namespace debug
{
    log::log( const std::wstring& ctx, int linenr, int type ): context( ctx ), LineNumber( linenr ), Type( type )
    {
        printf("\nLogging start! Context = %ls - Line = %d - Type = %d", context.c_str(), LineNumber, Type );
    }

    log::~log()
    {
        printf( "\nLogging end! Context = %ls - Line = %d - Type = %d", context.c_str(), LineNumber, Type );
        printf( "\nUsing Error here =%d", Error );
    }
    void log::Save()
    {
        FILE *fp = NULL;

        fclose( fp );
        fp = fopen( "mylogfile.log", "a" );
    }

}//namespace debug

}//namespace Logger

然后在main.h 我有:

#ifndef MYAPP_H
#define MYAPP_H

#include "Logger.h"

#define WIDEN2( x )     L ## x
#define WIDEN( x )      WIDEN2( x )
#define WFILE       WIDEN( __FILE__ )

#define __STR2WSTR( str )   L##str
#define _STR2WSTR(str)  __STR2WSTR(str)
#define WFUNCTION       _STR2WSTR( __FUNCTION__ )

#define DEBUGLOG_START( Type )  Logger::debug::log _debugLog( WFUNCTION, __LINE__, Type );
#define DEBUGLOG_SAVE   { _debugLog.Save(); }

#endif //MYAPP_H

最后在main.cpp 我有:

#include "Test_UserPart.h"


int _tmain(int argc, _TCHAR* argv[])
{

DEBUGLOG_START( 1 )

Logger::debug::OtherNumber = 10;

_getch();
return 0;
}

当我想编译它时,我收到错误error LNK2005: "int Logger::debug::Error" (?Error@debug@Logger@@3HA) already defined in Logger.obj ...MyApp.obj

据我所知,我没有制作任何循环包含。但是为什么会出现这个错误呢?

谢谢!

【问题讨论】:

    标签: c++ windows class include


    【解决方案1】:

    您在标头中定义变量,当该标头包含在多个源文件中时会导致多个定义。相反,在标题中声明它们:

    extern int Error = 0, OtherNumber;
    ^^^^^^
    

    并在一个源文件中定义它们。或者停止使用全局变量。

    【讨论】:

    • 也许我做错了什么,但现在我得到:unresolved external symbol 错误。在Logger.h 现在我有extern int Error;,在main.cpp 我有::Logger::debug::Error = 0; 不幸的是有些值必须是全局的。或者我可以通过其他方式访问它们吗,形成 main?
    • 没关系,我想通了!谢谢!
    • @kampi 你发现了什么?
    • @Ollie:对不起,我不记得了。这是 3 多年前的事了,但可能我的意思是,如何访问变量。不幸的是,我无法再访问此代码了。
    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    相关资源
    最近更新 更多