Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function declaration and definition consistency

I have a source that tells me:

The source file that defines a function should include the header that contains that function’s declaration. That way the compiler will verify that the definition and declaration are consistent.

I'm not sure how this is right, what type of "consistency" are we talking about? Because if the definition and declaration weren't consistent in return type or argument type/number, the compiler would just think I was declaring a separate function and wouldn't verify anything at all.

E.g. If I had a header file test.h:

 void func();

And a source file testsource.cpp:

 #include <iostream>
 #include "test.h"
 using namespace std;

 void func(int x){
     cout << "Hello StackOverflow" << endl;
 }

If I were to run this program the compiler would just think func() and func(int) were different functions and wouldn't throw up a fuss about consistency. What type of consistency is it referring to?

like image 272
Silversonic Avatar asked Feb 22 '26 16:02

Silversonic


2 Answers

An interesting question. Your "source" [I assume that's a person or a book, or...] is wrong. Even though it's a common convention to have function declarations in a header file with the same base name as the file contain the function body, there's no requirement to do so.

Other than, of course, good coding standards.

You are correct, two functions with the same name but different arguments are perfectly acceptable -- as is declaring a function but never defining it (as long as you never call it.)

The C++ compiler does not keep you from shooting yourself in the foot, but good coding practices do.

Now that you edited the quote from the book into the question, I can point out that the quote says "should" not "must". The common-sense usage is neither mandated nor enforced by the language. It is simply good programming practice.

Also note that lint-type programs may well detect and complain about this, even though the compiler doesn't.

like image 70
Dale Wilson Avatar answered Feb 25 '26 08:02

Dale Wilson


If you have another compilation unit that depends on your func, say, a bar.cpp defined this way:

#include "test.h"

void bar()
{
    func();
}

This compilation unit imports your header and the compiler will assume that there will be another object file that defines whatever is declared in that test.h header.

Now, if you only had your testsource.cpp define a different function, instead (the one with different function signature), the compiler at this stage will complain of a linking error: the symbol func() referred to in bar.cpp cannot be found anywhere in its link inputs!

like image 23
Santa Avatar answered Feb 25 '26 08:02

Santa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!