slasher53
slasher53

Reputation: 141

C - Struct in multiple files without header file

I'm doing a college project in C which is quite strict in its requirements in that I'm not allowed to include any additional files or modify any header files.

I'm currently trying to implement a linked list to store some records and I need it to span over two .c files. Currently to use global variables I've been declaring variables in file1.c and then in file2.c using extern. But how do I go about doing this for structures as I've always just added it to the .h file?

Cheers

Upvotes: 3

Views: 296

Answers (2)

cdarke
cdarke

Reputation: 44344

It might seem daft to put such restrictions on your program, but I suspect your teacher is trying to get you to implement encapsulation.

Do you really need to use the struct in both files? Try to have one .c file that handles the struct, and expose operations on that struct as function calls.

For example: you might decide to have file2.c handling the struct. Declare the struct in file2.c before any functions, after any #include statements - in other words where you would include the header file if you had one.

Then, if you need to access the struct from file1.c, call functions in file2.c to do the job for you.

Try to avoid global variables, pass parameters instead. One typical global variable for a linked list might be the head (or anchor) pointer. You can have that as a static global in file2.c (or whichever is handling the linked list) and keep it hidden - there should be no need to share.

Once all the operations on the linked list are encapsulated in one file it becomes independant of the user code, and can be used in other programs.

Upvotes: 2

wallyk
wallyk

Reputation: 57774

Place the contents of what would be in the header file in each source file.

It is extremely difficult to discern why anyone would impose such a requirement. It is rather like being required to build a wood frame house without any tools made of metal. Any idea what it might be trying to teach?

Upvotes: 6

Related Questions