开发者

Headers and multiple sources

开发者 https://www.devze.com 2023-01-31 21:32 出处:网络
Hey. I have this in a header file: struct something { int a; int b; }; int all[25][9]; This header file is included in all 3 .c files that I have on my project. One of the files (the main file) has

Hey. I have this in a header file:

struct something {
        int a;
        int b;
};
int all[25][9];

This header file is included in all 3 .c files that I have on my project. One of the files (the main file) has the main function and the others have functions that are used in the main file. They also use variables that are declared on this main file, by using extern type variableName. However, while I do declare struct something *stuff; and later malloc it on the main file (and these other files work with this stuff direc开发者_如何学运维tly), my all 2d array isn't declared anywhere but the header file. I use this array in one of those extra .c files. Will this all array be declared in each of them? Should I do it this way? It's imperative that there's a reference to all in that header file, for my purposes. Should I just declare all as all[][] and then assign a size to it on the .c file, or something like that?


If you want multiple source files to share a single array called all you should declare

extern int all[25][9];

in the header and

int all[25][9];

in one of the c files.


Use extern keyword to declare the array in your header:

extern int all[25][9];

Then instantiate it in just one of the implementation files:

int all[25][9];

Other C files include the header and can access the array.


You should not do it this way. This way creates a definition of all in every source file that includes the header, and multiple definitions of the same object are not allowed (in pratice, you might get a seperate instance of all in each source file, or they might all refer to the same one).

Instead, in the header file, put only declarations:

extern int all[25][9];

Then in one C file (probably your "main" file you mention), put the definition:

int all[25][9];


In the header file define/declare as

EXT int a;

In the main c file use

#

define EXT  extern
#include <a.h>
#undef EXT

This will avoid seperate definition /declaration

0

精彩评论

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

关注公众号