Search code examples
c++header

Can I define a macro in a header file?


I have a macro definition in MyClass.h, stated as such:

#define _BufferSize_ 64

I placed the include directive for MyClass.h inside of main.cpp:

#include "MyClass.h"

Does this mean I can use _BufferSize_ in both main.cpp and MyClass.h? Also, is this good practice?


Solution

  • Yes, it would work. (Disregarding the problem with underscores that others have pointed out.)

    Directive #include "MyClass.h" just copies the whole content of file MyClass.h and pastes it in the place of the #include. From the point of view of the compiler there is only one source file composed of the file specified by the user and all included files.


    Having said that, it would be much better if you use in-language construction instead of preprocessor directive. For example replace:

    #define _BufferSize_ 64
    

    with

    constexpr size_t BufferSize = 64;
    

    The only thing it does differently than the #define is that it specifies the type of the value (size_t in this case). Beside that, the second code will behave the same way and it avoids disadvantages of preprocessor.

    In general, try to avoid using preprocessor directives. This is an old mechanism that was used when c++ coudn't do that things in-language yet.