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?
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...
I use forward declaration only when the function is used only in that file.
If you want to make it available to other units you use a header file, and then you don't use forward declaration (unless you are solving a very specific problem such as circular dependencies). Don't use both. Never make the same declaration in more than one place.
Edit
Forward declaration of classes is a different case from what you asked about:
Should one use forward declarations instead of includes wherever possible?
Your update
Don't write your header files like that is the simple answer. Header files should as far as possible be self-contained, and not contain anything unrelated to the 'public' interface. (I put 'public' in quotes because when you declare a C++ class the protected and private methods have to go in the same 'public' header file. But you should still avoid putting things in the header file that don't really need to be there.)
That said, if you have no choice over the matter, it is still better to include the relevant header file than to duplicate the declaration. Maintainability is usually more important than compilation speed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With