c++ - 编译器就像未定义预处理器指令一样工作

标签 c++

我有一个头文件及其 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.cppError.cpp 是不同的翻译单元。您仅为 main.cpp 定义宏,而不为 Error.cpp 定义宏。

您应该将您的 #define 指令放在两个 .cpp 文件包含的头文件中,或者在项目设置/makefile 中定义这些宏。

关于c++ - 编译器就像未定义预处理器指令一样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29178362/

相关文章:

c++ - 为什么 V8 的 Hello World 在 Ubuntu 上会导致段错误?

c++ - osx : external program (qprocess) crash if parent run with open, 但如果父级直接运行则工作正常

c++ - 特化主模板时,更特化意味着什么?

c++ - 是否还有理由在 C++ 代码中使用 `int`?

c++ - 读取未知长度的数字

C++ Mutexes-检查是否有另一个线程在等待

c++ - 通过 operator[] 和 .at() 访问 vector 的负索引

c++ - 我可以将隐式初始化重载为 0 吗?

c++ - Malloc C 和 C++ 代码兼容性

c++ - 如何遍历 boost::mpl::list?