Include header files optionally in C++

有些话、适合烂在心里 提交于 2019-12-25 16:08:40

问题


I have a C++ code which needs to include a certain library in some servers and not in other servers. I build my code using bjam.

Code example:

if server in server_list:
   include <header-file.h>
   int function();
else:
   int function();

And during build using bjam:

if server in server_list:
    -llibrary
else:
   ...

回答1:


Header file inclusion is a compile time activity not run time. So you can't use if conditions for the same

use #ifdefs

#define SERVER_IN_LIST

#ifdef SERVER_IN_LIST
    #include<...>
#endif



回答2:


In C and C++ any line that begins with a # is a pre-processor directive. The pre-processor is a text parser that parses a source code file before it is compiled. It understands particular directives such as #include, #define and #ifdef but it treats normal C++ code as if it were text. For this reason, you can't use normal C++ code to alter the interpretation of the pre-processor directives.

Let's look at an example:

if (x == 4){
    #include "x4.h"
}

The above is wrong because the if statement and its braces are part of the C++ code so will be ignored by the pre-processor. The pre-processor will go straight ahead and interpret the #include directive, which will cause the contents of x4.h to be pasted into that position in the file.

The correct way to write this is to use conditional pre-processor directives such as #if or #ifdef. For example...

#ifdef INCLUDE_X4
#    include "x4.h"
#endif

Note that the indentation in this code is optional.

More information about pre-processor directives can be found here.



来源:https://stackoverflow.com/questions/39741849/include-header-files-optionally-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!