C預處理器 - 在編譯時向元素添加元素

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章