我想将标题文件包含在程序中。是否有可能,如果是,我该怎么办?
我的想法是做这样的事情:
switch(opt)
{
case 0:
{
#include "matrix.h"
break;
}
case 1:
{
#include "grid.h"
break;
}
}
这就是我编写它的方式。是吗?
在编译时间您可以对的位控制标题文件
有条件地包含#ifdef MAGIC
#include "matrix.h"
#else
#include "grid.h"
#endif
在编译时间
gcc -D MAGIC=1 file.c
或
gcc file.c
但在上,不可能有条件地包含标头文件是不可能的。
这意味着您的伪代码不可能显示的内容。
我想在程序中将标题文件包含在有条件的条件下。是否有可能,如果是,我该怎么做?
是的,这是可能的。
C预处理器已经具有支持条件汇编的指令最好使用
#ifndef expr
#include "matrix.h"
#else
#include "grid.h"
#endif
如果尚未定义expr
,则matrix.h
获取,否则如果it is defined (
#define expr ) then
grid.h` get包括。
这是两种不同的事情。#include
是在编译时间时处理的预处理器指令。swicth
是C
关键字,在执行时间。
因此,您可以使用有条件的预处理器指令,以选择要包括的文件:
#ifdef MATRIX
#include "matrix.h"
#else
#include "grid.h"
#endif
,也可以同时包括两者,因为通常,是否包含无用的标头文件并不重要。
#include "matrix.h"
#include "grid.h"
switch(opt) {
case 0:
/* Do something with matrix functions */
break;
case 1:
/* Do something with grid functions */
break;
}