0

我有一段代码可用于不同头文件中定义的不同数据集的相同函数。这些头文件可能具有不同定义的相同变量。

我可以在调用代码时将参数传递给代码以指定要在哪个数据集上执行该功能。

我想做的是将此参数传递给代码,如果参数等于X,那么我使用headerX,或者如果参数等于YI,则使用headerY。

据我了解,头文件必须包含在 MAIN 之前。是否可以在 MAIN 之后包含头文件,以便我可以编写 if/else 语句来确定我正在调用哪个头文件?

如果我做不到,请帮我解决这个问题。

4

3 回答 3

1

简单地说,你就是做不到。您可以根据条件预先包含标题。只需在文件顶部使用#if-def 块。

但是你不能像 if else 那样包含它:

这是错误的

if(x == 1)
    #include "header1.h"
else
    #include "header2.h"

但是您可以在文件顶部执行此操作:

#if SYSTEM_1
    #include "system_1.h"
#elif SYSTEM_2
    #include "system_2.h"
#elif SYSTEM_3
    #include "system_3.h"
#endif

或者您可以只使用支持重载函数的 C++。

于 2012-07-26T20:01:11.423 回答
1

您可以使用 #ifdef - 块来确定在编译之前要使用的数据集。但是,如果您想要不同的数据集,则需要通过更改该定义来更改(重新编译)可执行文件。

否则,您将需要在 C++ 中编译,因为直接 C 不支持重载函数。

于 2012-07-26T19:49:18.277 回答
0

您可以使用宏预处理阶段进行简单的元编程。用类似的东西创建一个“interface_myFunc.h”

#define FUNCNAME(T) myFunc_ ## T

void FUNCNAME(theType)(theType t);

用类似的东西创建一个“implement_myFunc.h”文件

void FUNCNAME(theType)(theType t) {
 // do something with t
}

然后将此文件包含在另一个文件“myFunc.h”中

#define theType toto
#include "interface_myFunc.h"
#undef theType toto

#define theType tutu
#include "interface_myFunc.h"
#undef theType tutu

和类似的定义,“myFunc.c”

#define theType toto
#include "implement_myFunc.h"
#undef theType toto

#define theType tutu
#include "implement_myFunc.h"
#undef theType tutu

现代 C,C11,也有方法为你通过所谓的类型泛型宏创建的所有这些函数创建一个公共接口:

#define myFunc(X)              \
_Generic((X),                  \
         toto: FUNCNAME(toto), \
         tutu: FUNCNAME(tutu)  \
)(X)
于 2012-07-26T21:41:50.140 回答