简体   繁体   中英

How to avoid redefining preprocessor directives of static library?

I have a question related to preprocessor defines and static linkage. I have two cpp libraries, whereof the static Library B consumes thet static Library A. Library A uses preprocessor directives for changing includes, dependent on the plattform:

#ifdef BUILD_WINDOWS
    //DO stuff for windows
#else
    #error "Flag windows not defined"
#endif

During compilation of Library A to "L_WIN.lib" the BUILD_WINDOWS flag is defined (as input to compiler), uses L_WIN.lib the compiler complains about missing definitions of BUIL_WINDOWS flag. I am very confused, why Library B needs the redefinition of this, since the binaries of "L_WIN.lib" should provide this Information.

I could imagein this is about including the header files again in the Library B implementations, but how can I avoid this? Where is the conceptional error here?

Thank you in advance

The preprocessor runs before the compiler and linker directly on your source code. It knows nothing about libraries or binaries.

Remember that header inclusion is done by the preprocessor. It quite literally copy-pastes the contents of the header file into the file where the #include directive is found before handing that file off to the compiler. If a header file depends on a preprocessor token being defined, then that token needs to be defined anywhere that header gets #include d.


It's not totally clear what you're trying to accomplish with your BUILD_WINDOWS preprocessor flag. If your library can only be built and used on Windows, then (IMO) you should generally just leave the Windows-specific stuff un-guarded and let the toolchain fail when it can't find Windows.h or whatever. If you have Windows-specific code in a cross-platform library, you should generally look for the _WIN32 preprocessor flag that gets defined by default on Windows toolchains, and you probably don't want to generate a hard error if it's not defined, but rather fall back to POSIX or other platform-specific implementations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM