我有一个头文件及其 cpp 文件(Error.h、Error.cpp)。 cpp 文件对预处理器指令执行检查,但总是失败。
错误.h:
/*
Optional macros:
AE_EXIT_AT_ERROR
AE_CONSOLE_WRITE_AT_ERROR
*/
#pragma once
extern void aeError(const char *str, int code=1);
extern void aeAssert(bool b, const char *failStr = "assertion failed");
错误.cpp:
#include "Error.h"
#include <stdexcept>
#ifdef AE_CONSOLE_WRITE_AT_ERROR
#include <iostream>
#endif
void aeError(const char *str, int code)
{
#ifdef AE_CONSOLE_WRITE_AT_ERROR
std::cout << str << std::endl;
#endif
throw std::runtime_error(str);
#ifdef AE_EXIT_AT_ERROR
std::exit(code);
#endif
}
void aeAssert(bool b, const char *failStr)
{
if(!b)
aeError(failStr);
}
主要.cpp:
//define both macros:
#define AE_CONSOLE_WRITE_AT_ERROR
#define AE_EXIT_AT_ERROR
#include "Error.h"
//rest of code
//...
两者都是std::cout << str << std::endl;
和 std::exit(code);
不要编译(我“手动”检查了它,尽管它们也被 IDE,即 VS2010 标记为灰色)。
这可能是什么原因?
最佳答案
main.cpp
和 Error.cpp
是不同的翻译单元。您仅为 main.cpp
定义宏,而不为 Error.cpp
定义宏。
您应该将您的 #define
指令放在两个 .cpp 文件包含的头文件中,或者在项目设置/makefile 中定义这些宏。
关于c++ - 编译器就像未定义预处理器指令一样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29178362/