Function in separate .cpp file not working

closed account (Ey80oG1T)
So I have two separate files in a repository on VS. One of them has a function, and the other one calls the function. However, when I run the code, it gives me this error message:

1
2
3
error LNK2005: "void __cdecl CarDrives(class Car &)" (?CarDrives@@YAXAAVCar@@@Z) already defined in AbstractBaseClass.obj

fatal error LNK1169: one or more multiply defined symbols found


But when then function and main code are in the same file, everything runs fine. I have classes in the other file, and I can use them fine, but why can't I have functions in another file?
Last edited on
You are trying to define a function more than once. You can't do this. You can declare it as many times as you like, but the actual definition - the actual implementation of the function - only once.

If I had to bet, I would bet you're doing this in a header file, and including that header file in more than one cpp file.
Last edited on
closed account (Ey80oG1T)
I'm not. I just created a new .cpp file, but some classes and functions in it, and called it in another file. I only included the .cpp file in one file.
#include copies one file into another.

If you #included a cpp file into another cpp file, the you have everything from that cpp file twice. So if that cpp file contains a function definition, you have that function definition in your program twice.

As a general rule of thumb, #include of a cpp file is a bad sign.
closed account (Ey80oG1T)
Oh....

So how can I fix this? I have a file with both classes and functions in it. Could I put these into a header file or something?
The declaration goes into the header. The definition goes into the cpp. The project is told about the existence of both cpp files.

What are you using to build your code? An IDE? Or command line?
One definition rule: ODR

One definition only is allowed
may have many declarations, e.g. in header files
Last edited on
Topic archived. No new replies allowed.