开发者

C - how to set default values for types in C headers

开发者 https://www.devze.com 2023-02-02 12:35 出处:网络
I have some headers from a C++ background that use many pre-baked \"defaults\" for declared types. e.g.

I have some headers from a C++ background that use many pre-baked "defaults" for declared types. e.g.

// Header.

typedef struct
{
    float red;
    float green;
    float blue;
} RGBColor;

// Defaults.
const RGBColor kRGB_White = {1.0f, 1.0f, 1.0f};
const RGBColor kRGB_Black = {0.0f, 0.0f, 0.0f};

...

// Source file.

RGBColor aColor = kRGB_White;

Q. I need to convert these headers开发者_运维问答 in to C for compatibility reasons. Is there a way to re-create these default values for a C header, preferably without changing the data structures themselves?

thanks.


To prevent problems with duplicate global definitions, you'll want to change the declarations of your const structures in the headers to:

extern const RGBColor kRGB_White;
extern const RGBColor kRGB_Black;

And place the definitions in a single .c file that gets linked in.

An alternative is to change the const structures to be static so it doesn't hurt when they end up in several different modules:

static const RGBColor kRGB_White = {1.0f, 1.0f, 1.0f};
static const RGBColor kRGB_Black = {0.0f, 0.0f, 0.0f};

This might cause the objects to show up more than once in the final linked image, but today's linkers are probably smart enough to get rid of the duplicates (I think - some testing might be in order if the structs you're doing this with are large and/or numerous).

In case you're worried about using the consts to initialize other variables, this:

RGBColor aColor = kRGB_White;

is fine in C (it seems relatively common for programmers to think that C doesn't allow this for some reason - maybe it wasn't always allowed in pre-standard C?).


If you cannot move the default value declarations out of the header file, redefine them as macros:

// Might not be a clean solution...
#define kRGB_White {1.0f, 1.0f, 1.0f} 
#define kRGB_Black {0.0f, 0.0f, 0.0f}
0

精彩评论

暂无评论...
验证码 换一张
取 消