Is there a way to instruct a C++ compiler to skip rest of current file?
Once in a while some functionality has to be conditionally compiled. For example, there's class Logger
that is only used when WITH_LOGGING
macro is #defi开发者_Go百科ne
d:
// Logger.cpp
#ifdef WITH_LOGGING
#include <Logger.h>
// several hundred lines
// of class Logger
// implementation
// follows
#endif
which is not very convenient - unless the reader scrolls through the file he can't be sure that the matching #endif
is position at the end of file and so the whole file contents is excluded with the #ifdef
. I'd prefre to have something like this:
// Logger.cpp
#ifndef WITH_LOGGING
#GetOutOfThisFile
#endif
#include <Logger.h>
// several hundred lines
// of class Logger
// implementation
// follows
so that it's clear that once the WITH_LOGGING
is not #define
d the compiler just skips the rest of the file.
Is something like that possible in C++?
An easy way to clarify this would be to put the implementation in another file which is included:
file Logger.cpp:
#ifdef WITH_LOGGING
#include <Logger.h>
#include "logger.impl"
#endif
file logger.impl:
// several hundred lines
// of class Logger
// implementation
// follows
Why are you trying to exclude the contents of that file? If I understand correctly, the code in it would not be used if the define was not set. In that case, link-time optimization should remove those functions from the executable regardless.
This won't work if you have functions overridden from other libraries, but for the regular case (and most likely for logging) this will be enough. In GCC this is --ffunction-sections for the compiler and --gc-sections for the linker. Visual Studio should have comparable flags but I don't know what they are.
精彩评论