artic sol
artic sol

Reputation: 493

making a global struct pointer available to multiple source files

I have a struct declared in a header file called h1.h that included in two source files, c1.c and c2.c.

typedef struct
{
    char binary_filename[256];
}programming;

I want to create two variables of this struct, device1 and device2 and then declare two pointers to each of these variables, programmingPtr1 and programmingPtr2.

I want to be able to access the member, binary_filename of a instance in each of the source files.

I'm confused as to where I should declare these variables and pointers.

Should I declare the variables as extern in the header?

I read this post but it doesn't deal with pointers to variables.

Could someone advise please as to the best method?

Upvotes: 1

Views: 1816

Answers (2)

0___________
0___________

Reputation: 68059

You are not creating any instances - they are just two separate structures in the global scope. Same is with the pointer. You just need to inform the compiler that the object is defined somewhere else using keyword extern. Of course you need to have your typedef as well.

The actual "connection" between defined extern object and the physical objext will done by the linker.

Upvotes: 0

dbush
dbush

Reputation: 225757

To use variables in multiple source files, you'll need to declare them in a header file that all relevant sources include, then you define them in exactly one source file.

So your header would have:

extern programming device1;
extern programming device2;
extern programming *programmingPtr1;
extern programming *programmingPtr2;

Then in one source file, you would have:

programming device1 = { "filename1" };
programming device2 = { "filename2" };
programming *programmingPtr1 = &device1;
programming *programmingPtr2 = &device2;

Upvotes: 1

Related Questions