Function prototype vs include header in cpp

igor picture igor · Feb 8, 2013 · Viewed 9.7k times · Source

I have function that do some work.

A.h

void doSomething(int n);

A.cpp

#include "A.h"

void doSomething(int n) {
    /* something */
}   

If I want to use this function in another source file, what is the best choice:

1) include A.h

B.cpp

#include "A.h"

void anotherTask() {
    // ...
    doSomething(5);
    // ...
}

2) or use forward declaration (function prototype):

B.cpp

void doSomething(int);

void anotherTask() {
    // ...
    doSomething(5);
    // ...
}

There are many tips about using forward declarations as often as possible for classes. So, what's the best practice for function forward declaration?

UPD

Ok, this is too easy example.

What if header A.h have some garbage (relative to B.cpp that doesn't know anything about drivers level):

A.h

#include "specific_driver_header.h" /* some lowlevel stuff that B.cpp couldn't know */

#define SPECIFIC_DRIVER_DEFINES 0xF0  /* useless define for B.cpp that uses global namespace */

void doSomething(int n);   /* only significant function for B.cpp */

If I include A.h in B.cpp then B.cpp will be not driver independent or something like that. Should I use variant (2) in that case?

Answer

Mats Petersson picture Mats Petersson · Feb 8, 2013

Always use a prototype in a header when at all possible. This prevents accidentally making changes to the one place, and not the other.

For example, where change the function to:

void doSomething(long n);

Now there are two other places: the defintion of the function, and b.cpp prototype to change.

If you have a header, the compiler will at least have a chance of telling you that "this looks wrong". Rather than you getting a linker error late on...