Daft Question i think

This is a discussion on Daft Question i think within the C Programming forums, part of the General Programming Boards category; Hi There,
Basically i have two .c files and a .h file
One of the .c files contains a function:
...

Daft Question i think

if the declaration for this function is at the top of the c file it is in it builds perfectly, however second i move it into the header file i get errors. The reason i need the declaration in the header file is because it is called from the other .c file.

If you're moving the definition into the header file that's wrong*. Keep variable and function definitions out of .h files. .h files just describe the name and type of a thing, they shouldn't reserve storage space for variables, or have actual code in them.

All you need in the .h file is a function prototype, or declaration. Something like this:

Code:

extern TransferMessage(int Port, struct Device *example);

That extern keyword is to notify the linker** that the definition of the function will be in some other .c file. Thus, if the definition is in foo.c, and you #include this header in bar.c, the linker will see this extern function called TransferMessage. It wont worry about not being able to find it right away, in the same file. It will know that function exists externally to bar.c, in some other file.That semicolon is there just to tell the compiler there is no function body (definition) to follow, just a declaration.

One more note, all your header files should have include guards (link). They keep the compiler from complaining about multiple declarations, by preventing the same .h file from being included multiple times in the same translation unit. A translation unit is a technical term that is basically a .c file.

EDIT:
* It is okay to have the definition in a header file in some rare circumstances, most notably if you "inline" the function. That is a trick to help make your code faster, but it is something you should not bother with 99.9% (or more) of the time.

** The linker was traditionally a separate component from the compiler proper. It is still a separate entity in many implementations, but now the compiler usually handles both stages seamlessly. The compiler proper would turn a .c file into an object file (often suffixed .o), which contained (roughly) the machine code for the .c file. The linker would combine that object file with any other object files you specify, as well as libraries and "startup" and "cleanup" code. There is often code that runs before and after your main function, that sets up and cleans up behind the scenes stuff that you usually don't need to worry about.