Prototype of vs function include header in cpp

I have a function that does some work.

hijras

void doSomething(int n); 

a.cpp

 #include "Ah" void doSomething(int n) { /* something */ } 

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

1) include Ah

B.cpp

 #include "Ah" void anotherTask() { // ... doSomething(5); // ... } 

2) or use forward declaration (function prototype):

B.cpp

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

There are many tips for using advanced ads as often as possible for classes. So what is best for forward function declaration?

UPD

Well, this is too simple an example.

What to do if there is garbage in the Ah header (regarding B.cpp, which knows nothing about the driver level):

hijras

 #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 Ah in B.cpp, then B.cpp will not be driver independent or anything like that. Should I use option (2) in this case?

+4
source share
2 answers

Always use a prototype in the header when possible. This prevents accidental changes to one place and not another.

For example, if you change the function to:

 void doSomething(long n); 

Now there are two more places: function definition and prototype b.cpp for change.

If you have a title, the compiler at least has a chance to tell you that "it looks wrong." Instead of getting the linker error late ...

+6
source

I use direct declaration only when the function is used only in this file.

If you want to make it available to other devices, you use the header file, and then you do not use the forward declaration (unless you solve a very specific problem, such as circular dependencies). Do not use both. Never place the same ad in multiple places.

Edit

Redirecting class declarations is another case you asked for:

Should forward ads be used instead of being included where possible?

Your update

Do not write your header files as this is a simple answer. Header files should, as far as possible, be self-contained and contain nothing that is not associated with a “public” interface. (I put “public” in quotation marks because when you declare a C ++ class, protected and private methods must come in the same “public” header file. But you should still avoid putting things in the header file, which really don't need to be there.)

However, if you have no choice on this, it’s still better to include the appropriate header file than to duplicate the declaration. Maintaining health is usually more important than compilation speed.

+5
source

All Articles