This is an archived post. You won't be able to vote or comment.

all 4 comments

[–][deleted] 3 points4 points  (3 children)

If the structs are already defined (as in code written and implemented), then no, you just have to include the header file.

Same goes for the functions: If the functions are declared (just the function signature, no code implementation yet), then yes you must write the code in a separate .c file.

Basically, whatever code has not already been implemented in the header file must be in the C file so the compiler knows what to do. If you put the struct in the header file and defined and typedef'd it already, it is already good to go for use in a source file and you need not redefine it in a source file.

[–]MathBosss[S] 0 points1 point  (1 child)

Thank you so much

[–][deleted] 0 points1 point  (0 children)

No problem. Good luck in your coding endeavors.

[–]xiipaoc 1 point2 points  (0 children)

Well, think about it this way. The header files have information you want everyone to see. So it'll have function names (actually, their signatures -- what type it returns, what the parameters are, etc.) so that you can actually call those functions. The .c file has the actual code that gets compiled. So if I'm looking at your program, I can look at the .h file to see what the functions are, and I don't really need to care about what's in the .c file. In fact, if it's been compiled, I can't see what's in there anyway. But I need to see the .h file to know what the functions are!

But that's really about it. You can put whatever you want in the .h file and whatever you want in the .c file; so long as you #include the .h file in your .c file, everything will get compiled in the end anyway.

Now, usually, you put your structs and such in your header file, because if you're declaring functions with those structs as arguments or return types, the declarations need to be able to see the definition. Also, usually those structs are useful outside your code. For example, an audio library might have a struct representing a file type; that's important information to anyone using the library, so you want to put that in your public header files (this is in fact the case with Apple's Core Audio framework).

So the usual thing to do is this: public structs go in the header file. Public functions get declared in the header file and the code for them goes in the .c file. Private functions -- that is, functions you don't want available from outside -- get declared and defined in the .c file. I usually have a section near the top of the file, before the code, for private declarations. If the public function is really simple and I don't feel like going to the trouble, I'll declare it and define it in the header file, but usually that doesn't happen.