Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

c - Put shared definitions in an external file

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...