James Downer
James Downer

Reputation: 31

When to not put C function prototypes in header files

Is there a reason why it might not be good practice to place C/C++ function prototypes in header files but instead place them at the top of the main .c/.cpp file?

For example, I could write a dothis.c file:

#include "funcs.h"

int main(int argc, char ** argv) {
   // some code
   int result = doThis();
   // more code

   return 0;
}

int doThis(void) {
   // code and return value
}

And in my funcs.h file, I'd write:

#ifndef FUNCS_H
#define FUNCS_H

int doThis(void);

// more function prototypes

#endif // FUNCS_H

Is there any reason why it might be better to place the prototype(s) (assuming there are many) at the top of the .c/.cpp file instead? For example:

#include "funcs.h"

int doThis(void);

// more function prototypes

int main(int argc, char ** argv) {
   // some code
   int result = doThis();
   // more code

   return 0;
}

int doThis(void) {
   // code and return value
}

In the first case, I feel it would be helpful to have many function prototypes in a separate header file plus documentation to logically separate declaration from implementation and to make it easier to concisely see what the main file is doing.

Upvotes: 0

Views: 1499

Answers (1)

R Sahu
R Sahu

Reputation: 206627

Is there a reason why it might not be good practice to place C/C++ function prototypes in header files but instead place them at the top of the main .c/.cpp file?

The only time that makes sense to me is when the functions are implementation details of other functions. Of course, in that case, I prefer to define them in the file scope using file scoped functions using static qualifier or putting them in a namespace specific to the .cpp file.

For all other functions, I find it hard to justify not putting the declaration in a header file and #includeing the header file in the files that use the functions and in the file that defines the functions.

Upvotes: 2

Related Questions