Search code examples
c++cmakeclion

C++ multiple definition of function when moving to another file


I'm trying to refactor my C++ project moving some function from a cpp file (example.cpp) to another (utils.cpp) in order to sort the project and reuse the same functions in other sources.

example.cpp:

double std_dev(std::vector<double> Mean, std::vector<double> Mean2, int n,int i){
    if (n==0){
        return 0;
    } else{
        return sqrt((Mean2.at(n) - pow(Mean.at(n),2))/i);
    }
}

float mean(const float* x, uint n){
    float sum = 0;
    for (int i = 0; i < n; i ++)
        sum += x[i];
    return sum / n;
}

So, when i delete the function from example.cpp just by cutting the code and pasting to the file utils.cpp, and including the file utils.cpp in example.cpp:

#include "utils.cpp"


//deleted definition 

when i compile the project, the compiler fail giving the error: multiple definition of 'mean'.... multiple definition of 'std_dev', as if somehow the compilation I performed did not delete the function definitions in the example.cpp file.

I've also tried to:

  • delete the cmake-build-debug folder and reloading the project
  • compile the code without the functions definition (in order to have a clean compilation) and adding it in a later moment

what am I doing wrong?


Solution

  • A function can be declared several times (i.e. just the function prototype), and may not be defined several times (i.e. with body).

    This is why .h files with declarations are used and can be included anywhere, and the implementation remains in a single .cpp.


    The same holds for global variables: extern declaration in a header, definition in some source file.