McLovin
McLovin

Reputation: 3417

Compiler acts as if a preprocessor directive isn't defined

I have a header file and its cpp file (Error.h, Error.cpp). The cpp file performs a check on a preprocessor directive but it always fails.

Error.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");

Error.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);
}

main.cpp:

//define both macros:
#define AE_CONSOLE_WRITE_AT_ERROR
#define AE_EXIT_AT_ERROR
#include "Error.h"

//rest of code
//...

both std::cout << str << std::endl; and std::exit(code); don't get compiled (I checked it "manually", although they are also marked gray by the IDE, which is VS2010).

What might be the cause of this?

Upvotes: 0

Views: 64

Answers (1)

Anton Savin
Anton Savin

Reputation: 41301

main.cpp and Error.cpp are different translation units. You define the macro only for main.cpp, not for Error.cpp.

You should either put your #define directives in a header file included by both .cpp files, or define these macros in project settings/makefile.

Upvotes: 7

Related Questions