Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say I have the following construct

typedef struct Article {
    char * word;
    int code;
} Artcle;

And I want a bunch of files to have access to what amounts to:

Article THE = (Article) {.word="The", .code=87};
Article A   = (Article) {.word="A",   .code=79};
Article AN  = (Article) {.word="An",  .code=80};

What would be the proper way to put this into a shared article.c/h file? My first thought was doing:

// article.h
typedef struct Article {
    char * word;
    int code;
} Artcle;
Article THE = (Article) {.word="The", .code=87};
Article A   = (Article) {.word="A",   .code=79};
Article AN  = (Article) {.word="An",  .code=80};

But this is obviously wrong with the multiple definitions for the Articles. What would be the proper way to do this then?


One possible way to do this (I thought) was:

// article.h
typedef struct Article {
    char * word;
    int code;
} Artcle;
extern Article THE;
extern Article A;
extern Article AN;

// article.c
#include "article.h"
Article THE = (Article) {.word="The", .code=87};
Article A   = (Article) {.word="A",   .code=79};
Article AN  = (Article) {.word="An",  .code=80};

Additionally, what are these 'shared variables' referred to as?

question from:https://stackoverflow.com/questions/65946173/put-shared-definitions-in-an-external-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
144 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your last approach looks good, and is the normal way to do this. The only thing I'd change is that it's not necessary to use compound literals to initialize objects. You can simply write Article THE = {.word="The", .code=87}; and so on, without the (Article) cast-like syntax.

Additionally, what are these 'shared variables' referred to as?

They're simply global variables. Or, to be more formal, they are variables with file scope, external linkage, and static storage duration.

Note that if you don't intend to modify them over the course of the program, you should declare and define them as const. Global variables are generally considered a poor programming practice, but global constants don't have the same issues.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...