如何使用在应用程序中定义的新值 header 覆盖 "default" #define C ++ 库 header 的值

How to override "default" #define values ​of a C ++ library header with new values ​defined in an application header

我想做的是提供一个库,其中包含库 header 中的 #define 指令设置的一些默认值。这些将决定库代码的哪些功能将与给定的应用程序一起编译。如果应用程序开发人员需要添加或删除库函数,则应在不修改库的情况下用新值“覆盖”库的默认值。除了修改库编译代码外,那些应用程序 header 的 #define 值将依次添加或删除应用程序代码本身的部分内容。这是针对嵌入式系统的,因此即使是很小的内存节省也很重要。

下面是4个测试文件。即使有可能做到这一点,我也无法让它工作。也许正确的问题是:项目文件中 #define / #undef 的正确顺序是什么?

library.h:

#ifndef MY_LIBRARY_H
#define MY_LIBRARY_H

#include <stdio.h>

#define FUNCTION_1 true
#define FUNCTION_2 false

class Class {
   public:
    Class();
    ~Class();
#if FUNCTION_1
    void Function_1(void);
#endif
#if FUNCTION_2
    void Function_2(void);
#endif
};

#endif  // MY_LIBRARY_H

library.cpp:

#include "library.h"

Class::Class() { /* Constructor */ };
Class::~Class() { /* Destructor */ };

#if FUNCTION_1
void Class::Function_1(void) {
    printf("Hi, this is %s running ...\n\r", __func__);
}
#endif

#if FUNCTION_2
void Class::Function_2(void) {
    printf("Hi, this is %s running ...\n\r", __func__);
}
#endif

tst-09.h

#ifndef TST_09_H
#define TST_09_H

#include <library.h>

#undef FUNCTION_2        // .....................................................
#define FUNCTION_2 true  // THIS IS WHERE I'M TRYING TO OVERRIDE THE LIB DEFAULTS

#endif  // TST_09_H

tst-09.cpp:

#include "tst-09.h"

int main(void) {
    Class object;
#if FUNCTION_1
    object.Function_1();
#endif
#if FUNCTION_2
    object.Function_2();
#endif
}

利用链接器的功能。如果您想从二进制文件中排除未使用或不必要的代码,一种方法是将每个函数放在其自己的源模块中。 (一些编译器包支持 函数级链接 ,其中链接器可以删除未引用的函数。)

尝试按照您在问题中显示的方式使用宏需要在命令行上定义它们(并且库会随着任何更改而重建)。