Search code examples
c++compilationfunction-declaration

Why is the mismatch between declaration and definition not raising error during compilation?


I have two source files, main.cpp and math.cpp, along with a header file math.h. The code is as follows:

// main.cpp
#include "math.h"
#include <iostream>
int main()
{
    std::cout << add(5, 10);
    return 0;
}


// math.cpp
#include "math.h"
int add(int x)
{
    return x;
}


// math.h
int add(int x, int y);

I have intentionally created a mismatch between the declaration and definition of add.

Since I have included math.h in math.cpp, I expect the compiler to raise an error when I run the command clang++ main.cpp math.cpp -c. Instead, the compilation succeeds.

I understand that the mismatch will eventually cause an error at link-time but can someone explain why the compilation is succeeding in this case?


Solution

  • This code is legal:

    #include <iostream>
    
    int add(int);
    int add(int a, int b) {
        return a + b;
    }
    
    int add(int x) {
        return x + 1;
    }
    
    int main() {
        std::cout << add(1, 2) << '\n'; // calls two-argument version
        std::cout << add(3) << '\n';    // calls one-argument version
        return 0;
    }
    

    It's simply function overloading. If the single-argument version isn't used it doesn't have to be defined:

    #include <iostream>
    
    int add(int);
    int add(int a, int b) {
        return a + b;
    }
    
    // int add(int x) {
    //     return x + 1;
    // }
    
    int main() {
        std::cout << add(1, 2) << '\n'; // calls two-argument version
        // std::cout << add(3) << '\n';    // calls one-argument version
        return 0;
    }
    

    Putting the declaration of int add(int) into a header doesn't change the meaning of the code.