Reputation:
I think I am having a similar problem to LNK2005, LNK1169 errors, "int __cdecl g(void)" (?g@@YAHXZ) already defined but I cannot find the issue.
I am working with Visual Basic and I am having the following files
main.cpp
#include <iostream>
#include "functions.h"
using namespace std;
int main(){
number();
return 0;
}
I had a functions.cpp
but after reading the question I linked before I renamed it for functions.h
int number(){
int i = 1;
return i;
}
Now it is displaying error LNK2005: "int __cdecl number(void)" (?number@@YAHXZ) already defined in functions.obj
Is there anything wrong with the function number()
in functions.h
?
Upvotes: 2
Views: 6072
Reputation: 4876
Your immediate issue is that the functions.obj
contains code that is being linked in. Then you redefine number()
in main.cpp
so they collide. Go ahead and clean the project (which should delete functions.obj
, and you should be able to compile. I, however, recommend doing it this way.
functions.hpp (or functions.h)
int number();
functions.cpp
int number(){
int i = 1;
return i;
}
main.cpp
#include <iostream>
#include "functions.h"
using namespace std;
int main(){
number();
return 0;
}
When you compile, your program will create 2 objects with compiled code functions.obj
, and main.obj
. Since you use number
in the main file, the compiler looks for the implementation of that function. Since the implementation of that function is in the functions.obj
object, then you need to link that in.
If you are going to use number()
across several C++ files, then you should always separate the code out into its own file and implementation.
Upvotes: 5
Reputation: 28932
In one of the modules you link in there is a function with the name number()
. You define you own implementation so the linker does not know which one to use.
Either rename your function or use namespaces.
Upvotes: 0
Reputation: 9097
functions.h should only declare the functio, as in
int number();
then functions.cpp should contain the function definition
int number(){
int i = 1;
return i;
}
Of course functions.cpp needs to be compiled (add it to the project).
The problem here is that you are including functions.h in multiple files. The issue could be avoided also by simply declaring the function static
as in
static int number(){
int i = 1;
return i;
}
However, since it seems you are just learning, I would suggest you to study the basics of compiling c++ code.
Upvotes: 2