MSVC 多行宏编译器错误

MSVC multiline macro Compiler errors

我在header中定义了一个宏,宏所基于的函数也在同一个header中。

这是一个非常基本的示例,不是确切的代码,但希望它足以说明问题:

myMacro.h:

    #ifndef MYMACRO_H
        #define MYMACRO_H

        #ifdef _DEBUG
            bool myAssertFn(int test, char const* desc, char const* file, int line) {
                if (test != 0) {
                //Test passes, no action required
                    return true;
                }
                std::string msg;

                if (desc != nullptr) {
                    msg += "\n Context: ";
                    msg += desc;
                }
                if (file != NULL) {
                    msg += "\n    File: ";
                    msg += file;
                }
                if (line > 0) {
                    msg += "\n    Line: ";
                    msg += std::to_string(line);
                }
                //Construct filename
                time_t tClock = time(0);
                char szTime[24];
                tm tmNow;
                //Get system time
                localtime_s(&tmNow, &tClock);
                //Assertion Log File, path and name
                static const char* assertLogFile = "./ALF.log";
                //Build time / date of day prefix
                sprintf_s(szTime, sizeof(szTime), "%04d/%02d/%02d %02d:%02d:%02d "
                        , tmNow.tm_year + 1900, tmNow.tm_mon + 1, tmNow.tm_mday
                        , tmNow.tm_hour, tmNow.tm_min, tmNow.tm_sec);
                //Does file exist?
                std::ofstream logFile(assertLogFile, std::ios_base::app);
                //Write the content to the file
                logFile << szTime << msg.c_str() << std::endl;
                return false;
            }
            //Macro
            #define myAssert(test, desc)\               
                        myAssertFn((test), (desc), __FILE__, __LINE__)      
        #else
            #define myAssert(test, desc)\
                        (void)0
        #endif
    #endif

此宏的目的是包含调试信息并替代标准断言函数,并具有将结果记录到文件的额外好处。

问题是在编译时我得到:

error C2065: 'test' : undeclared identifier
error C2065: 'desc' : undeclared identifier

在源文件中使用宏的其他错误:

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2365: 'myAssertFn' : redefinition; previous definition was 'function' myAssert.h(37) : see declaration of 'myAssertFn'
error C2078: too many initializers
error C2143: syntax error : missing ';' before 'const'

在任何需要此宏的源文件中,我只需包含 header 并按如下方式使用宏:

    myAssert(ptr != NULL, "ptr != NULL");

如果测试 returns 0 那么描述将被记录到文件中,其中包含日期、时间戳、文件名和故障发生的行号。

对于多行宏,\ 字符必须是该行的最后一个。

即使是空格也会破坏多行宏,并且行尾有多个空格。

当你定义时,你有尾随字符:

#define myAssert(test, desc)\               
                              ^^^^^^^^^^^^^^

这意味着您的反斜杠适用于 space 而不是末行,因此 myAssertFn((test), (desc), __FILE__, __LINE__) 用法不再是宏的一部分。

你在源文件上的错误可能是因为你没有从头文件中删除定义,所以出现了重定义错误。