c++ - 变量已在 .obj 中定义,但没有循环包含

标签 c++ windows class include

<分区>

我知道,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

据我所知,我没有做任何循环包含。但为什么会出现此错误?

谢谢!

最佳答案

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

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

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

关于c++ - 变量已在 .obj 中定义,但没有循环包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30059424/

相关文章:

php - 使用 php 调整图像大小

c++ - 具有有效特化的未初始化模板类中的 static_assert

c++ - VC++允许/##/作为宏的值——如何在eclipse/mingw-gcc中处理它?

c++ - 打印的 CDC 在纸上显得很小

windows - 确定是否已从命令行 (cmd) 启动/执行批处理脚本 - 或 - 暂停或不暂停?

Python初学者类变量错误

c++ - 可变参数模板成员函数的部分特化

Windows CPU 调度程序 - 非常高的内核时间

c++ - Windows 下的异常处理和堆栈跟踪(MinGW/gcc)

python - Python 类可以应用双向重载吗?