Search code examples
c++staticexternlinkagefunction-prototypes

Is it legal / good to put function prototype of a function defined in a different source (not header) file?


I'm not sure whether my description describes the issue appropriately. I found this when I try to understand external linkage and internal linkage. Say I have a project containing 2 files:

//A.cpp
#include <iostream>
void doSomething();
int main()
{
    doSomething();
    return 0;
}

//B.cpp
#include <iostream>
void doSomething()
{
    std::cout << "Doing it" << std::endl;
    std::cin.get();
}

Note that neither of the two files is a header. They merely provide 2 translation units.

I'm astonished to find that this can compile and work correctly. I'm used to writing codes like this to avoid the multi-definition error when I have the same utility function (like linear interpolation) in different files:

//A.cpp
#include <iostream>
static void doSomething()
{
    std::cout << "Doing it" << std::endl;
    std::cin.get();
}
int main()
{
    doSomething();
    return 0;
}


//B.cpp
#include <iostream>
static void doSomething()
{
    std::cout << "Doing it" << std::endl;
    std::cin.get();
}
/* some other functions that call doSomething() */

This is obviously redundant, and the approach above seems to solve it. But I wonder is this really an accepted style? One cannot even find the definition of the function without the help of an IDE.


Solution

  • The first block of code is legal but it is not good practice. It's better to create a .h file where you put function prototype and #include the .h file in all the .cc files that use the function.

    //B.h
    #ifndef B_H
    #define B_H
    void doSomething();
    #endif
    
    //A.cpp
    #include <iostream>
    #include "B.h"
    int main()
    {
        doSomething();
        return 0;
    }
    
    //B.cpp
    #include <iostream>
    #include "B.h"
    
    void doSomething()
    {
        std::cout << "Doing it" << std::endl;
        std::cin.get();
    }