-1

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?

VitoShade
  • 3
  • 2
  • 2
    `#include "utils.cpp"` never include a cpp file. Instead create a `utils.h` and put declarations in that with your definitions in your `cpp` file. – drescherjm Oct 28 '22 at 13:46
  • This is what you're doing wrong: "including the file utils.cpp in example.cpp". Read about how to structure your code with headers, for instance in a good book. – molbdnilo Oct 28 '22 at 13:46
  • @drescherjm: "never..." unless you know what you are doing :-) –  Oct 28 '22 at 13:48
  • I would just give it a different extension if I really wanted to include. – drescherjm Oct 28 '22 at 13:52
  • *"and including the file utils.cpp..."* **Never include a source file.** Learn about forward declarations. [What are forward declarations in C++?](https://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c). – Jason Oct 28 '22 at 14:04

1 Answers1

0

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.