首页 > 解决方案 > 宏未到达 .c 文件

问题描述

仅当定义了宏时,我才尝试从标头启用一组功能

我在包含任何内容之前定义了宏,它到达 .h 文件并突出显示正确的函数,但它没有到达 .c 文件,因此我可以使用正确的原型调用函数,但它们没有定义,因为 .c 文件确实没看到我定义了宏

有没有办法让它工作而不必将所有 .c 代码填充到 .h 文件中?

例子:

测试.h:

#ifdef _ENABLE_
int enabled_function(int a, int b);
#endif

测试.c:

#ifdef _ENABLE_
int enabled_function(int a, int b)
{
    return a + b;
}
#endif

主.c:

#define _ENABLE_

#include "test.h"

int main()
{
    printf("%d", enabled_function(10, 10));
}

标签: cmacros

解决方案


您需要在头文件和 C 文件中使用条件编译

在头文件中:

#define SOMETHING


#ifdef SOMETHING
int a(int);
int b(int);
int c(int);
#endif

在 C 文件中:

#include "header_file_with_SOMETHING_declaration.h"

#ifdef SOMETHING
int a(int x)
{
    /* ... */
}

int b(int x)
{
    /* ... */
}

int b(int x)
{
    /* ... */
}
#endif

推荐阅读