C Preprocessor - Add Elements to Struct at Compile Time[CHINESE]  C预处理器 - 在编译时向元素添加元素

I am trying to think of a way to add elements to a struct at compile time, but by defining this in another file. For example:

我试图想一种在编译时向结构添加元素的方法,但是在另一个文件中定义它。例如:

defA.h:

defA.h:

typedef struct A {
    int element1;
    int element2;
} A;

otherfile.c:

otherfile.c:

#include "defA.h"

typedef struct B {
    int element1;
} B;

ADD_ELEMENT_TO(A, B, element3)

Would result in:

会导致:

struct A {
    int element1;
    int element2;
    B element3;
};

Can anyone think of a way to achieve this or something similar? I want to be able to control this by choosing to compile otherfile.c or not with the rest of the build.

任何人都可以想到实现这个或类似的方法吗?我希望能够通过选择编译otherfile.c或不与构建的其余部分来控制它。

1 个解决方案

#1


2  

Any solution using C preprocessor features is going to make a mess where the structure is declared. For example:

使用C预处理器功能的任何解决方案都会在声明结构时弄乱。例如:

Main source/header:

主要来源/标题:

#include "SpecialSauce.h"
…
typedef struct A {
    int element1;
    int element2;
    SpecialStuff
} A;

If the customer just bought the base software, SpecialSauce.h contains:

如果客户刚刚购买了基础软件,SpecialSauce.h包含:

#define SpecialStuff

If the customer contains extra, SpecialSauce.h contains:

如果客户包含额外的,SpecialSauce.h包含:

#define SpecialStuff int element3;

And, of course, one will need code that does or does not use element3 according to which version of the software is present.

当然,根据存在哪个版本的软件,需要使用或不使用element3的代码。

All of this can be controlled by preprocessor directives, and it can often be kept not too messy by giving it proper care. But commercial pressures often preclude that and result in software growing messier and in maintenance being neglected. So these sort of kludges will grow ugly and costly.

所有这一切都可以通过预处理器指令来控制,并且通常可以通过给予适当的关注来保持不太混乱。但商业压力往往排除了这种压力,导致软件越来越混乱,维护工作也被忽视。因此,这些类型的kludges将变得丑陋和昂贵。

Another alternative is to keep master source files and use them to generate source files with selected options. Only the generated source files would be provided to customers, and they would not have ugly preprocessor conditions. However, this creates a need for software to process the master source files, which itself must be maintained, and the master source files still have to have some sort of conditions, which you might be able to keep nice since they are under your control, but, again, real-world software has a tendency to grow messy.

另一种方法是保留主源文件并使用它们生成具有所选选项的源文件。只有生成的源文件才会提供给客户,并且它们不会有丑陋的预处理器条件。但是,这需要软件来处理主源文件,这些源文件本身必须维护,并且主源文件仍然必须具有某种条件,您可以保持良好状态,因为它们在您的控制之下,但是,真实世界的软件再次变得凌乱


本文转载自:http://www.itdaan.com/blog/2018/07/30/25884574760dca123c1c3a5e4ff1d698.html