C++ Cannot instantiate a class from another file in main.cpp - c++

I cannot get this to work
Addr.h
#ifndef ADDR_H
#define ADDR_H
class Foo{
public:
Foo(); // function called the default constructor
Foo( int a, int b ); // function called the overloaded constructor
int Manipulate( int g, int h );
private:
int x;
int y;
};
#endif
Addr.cpp
#include "addr.h"
Foo::Foo(){
x = 5;
y = 10;
}
Foo::Foo( int a, int b ){
x = a;
y = b;
}
int Foo::Manipulate( int g, int h ){
return x = h + g*x;
}
main.cpp
#include "addr.cpp"
int main(){
Foo myTest = Foo( 20, 45 );
while(1){}
return 0;
}
What am i doing wrong? I get these linker errors:
error LNK2005: "public: int __thiscall Foo::Manipulate(int,int)" (?Manipulate#Foo##QAEHHH#Z) already defined in addr.obj c:\Users\christian\documents\visual studio 2010\Projects\Console Test\Console Test\main.obj
error LNK2005: "public: __thiscall Foo::Foo(int,int)" (??0Foo##QAE#HH#Z) already defined in addr.obj c:\Users\christian\documents\visual studio 2010\Projects\Console Test\Console Test\main.obj
error LNK2005: "public: __thiscall Foo::Foo(void)" (??0Foo##QAE#XZ) already defined in addr.obj c:\Users\christian\documents\visual studio 2010\Projects\Console Test\Console Test\main.obj
error LNK1169: one or more multiply defined symbols found c:\users\christian\documents\visual studio 2010\Projects\Console Test\Release\Console Test.exe
I would appreciate any kind of help!!!

#include "addr.cpp"
You're including the .cpp file to your main.cpp, which is what causing the problem. You should include the header file instead, as:
#include "addr.h" //add this instead, to your main.cpp
Because its the header file which is containing the definition of the class Foo.

In main.cpp, you should include the header file, rather than the cpp file.
Change
#include "addr.cpp"
To
#include "addr.h"

In main.cpp
#include "addr.cpp"
should be
#include "addr.h"
If you #include "addr.cpp", you can compile main.cpp (and even link it into an executable on it's own), but when you link main.obj and add.obj, you get a duplicate definition error, because class Foo is now fully defined in both object files.

You can either #include "addr.h" (as already stated), or make the build system not compile addr.cpp. The former is usually preferred, though the latter would also solve the trouble and is often used with automatic code generation tools' output.

There are two ways of getting the class data into main.cpp
1) include the header file "addr.h" in the main.cpp file, so now you have the class and member functions' definitions, but don't have the implementation part of them. So while compiling, the code should be :
g++ addr.cpp main.cpp.
2) include the cpp file "addr.cpp" in the main.cpp, so you automatically have the definitions also as "addr.h" is included in "addr.cpp". Now you must compile only the main.cpp file: g++ main.cpp.
First method is standard and is a good programming practice for maintaining modularity and encapsulation...

Related

Cannot make function public. Getting: "LNK2005" error. How to debug linker errors

there is only one definition of MyFourierClass::forward_fft in my project. When I declare MyFourierClass::forward_fft as public, I get this error, otherwise there is no error.
Error Message:
1>my_fourier.obj : error LNK2005: "public: void __cdecl MyFourierClass::forward_fft(int)" (?forward_fft#MyFourierClass##QEAAXH#Z) already defined in main.obj
1>CGPProject\x64\Debug\CGPProject.exe : fatal error LNK1169: one or more multiply defined symbols found
my_fourier.cpp:
#ifndef MY_FOURIER
#define MY_FOURIER
class MyFourierClass {
double** dataset = 0;
//public: // <-- un-commenting this line causes the linker error.
void forward_fft(int);
};
void MyFourierClass::forward_fft(int bins) {
bins = bins + 1;
};
#endif
Main:
#ifndef MY_MAIN
#define MY_MAIN
#include "my_fourier.cpp"
int main() {
int i = 0;
}
#endif
is there a standard method for debugging linker errors? I thought there might be a definition in another file, so I've delete all other files in my project. There is now only main.cpp and my_fourier.cpp. I'm using Visual Studio 2019.
Thanks in advance.
As you included the module my_fourier.cpp in the module with main using the include directive
#include "my_fourier.cpp"
then this function
void MyFourierClass::forward_fft(int bins) {
bins = bins + 1;
};
is defined at least twice.
You should place the class definition in a header and this header include in the module
my_fourier.cpp where the member function is defined and in the module with main removing from the last module the directive
#include "my_fourier.cpp"

"unresolved external..." when trying to build a class with CPP

Today I downloaded the new version of visual studio, and I tried to build a class:
class Fraction
{
public:
Fraction(int, int);
private:
int _a;
int _b;
};
I also built a cpp file for the implementation:
#pragma once
#include "Fraction.h"
#include <string>
Fraction::Fraction(int a, int b)
{
_a = a;
_b = b;
}
The header file (thc class) is in file called "Franctions.h" and found in the header files directory.
The cpp file (thc class) is in file called "Franctions.cpp" and found in the Resource files directory.
When Im trying to run this simple program, I get this issue:
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol "public: __thiscall Fraction::Fraction(int,int)" (??0Fraction##QAE#HH#Z) referenced in function _main Homework2 c:\Users\VVV\documents\visual studio 2017\Projects\Homework2\Homework2\questionA.obj 1
Why can it be happening?
EDIT:
main:
#include "Fraction.h"
int main()
{
Fraction f1(1, 2);
return 0;
}
The problem is not within your Fractions.h or Fractions.cpp, but rather with questionA.cpp note that the referencing file that cannot find the symbol in the error is:
c:\Users\VVV\documents\visual studio 2017\Projects\Homework2\Homework2\questionA.obj
Is #include "Fractions.h" in that file?
this error means that the compiler can't find this function.
write the specific place in the include path and see if it solve your problem.
if so, it means your header file is looking at different directory than the one you think.

MFC projects cause "multiple definition" linker errors?

Is there something special about how an MFC project handles includes?
Here's the scenario. I like to define my class member functions in the h file, instead of splitting up a class between two files.
In Visual Studio I can create an empty Win32 project and do something like this:
main.cpp:
#include "doubleDef.h"
int main()
{
doubleDef t;
t.func();
return 0;
}
doubleDef.h:
#pragma once
class doubleDef
{
public:
int func();
};
int doubleDef::func()
{
return 4;
}
This builds just fine.
If I take doubleDef.h into an MFC dialog project, and add #include "doubleDef.h" to the h file of the main dialog, I get LNK2005, saying that func is already defined, making it seem as if the #pragma once is being ignored.
If I instead include doubleDef.h in the main dialog's cpp file, everything is fine. But in the empty Win32 I can include doubleDef.h "multiple times" by doing this:
Header.h
#pragma once
#include "doubleDef.h"
Header1.h
#pragma once
#include "doubleDef.h"
main.cpp:
#include "Header.h"
#include "Header1.h"
int main()
{
doubleDef t;
t.func();
return 0;
}
That is, it appears #pragma once works as expected (prevents multiple definitions of doubleDef::func()).
If I turn doubleDef into a template class, then the function definition must be in the h file. Likewise, I can make func inline, either by adding the keyword or implicitly by defining it next to the declaration in the class (as in int func() {return 4;}), and then, again the definition must be in the h file.
According to the documentation, the compiler treats inline as more or less optional, so it seems like if I just want to keep everything in the h file, I can just make everything inline.
What gives?
The #pragma once means the file will only be included once per source file. If you have many source files including it, you will still get a copy in each source file.
By declaring a function inline, you tell the compiler it's OK to have multiple copies - as long as those copies are identical.
The usual way of working is to have the declarations in the header file, and the definitions (implementation) in another source file.
P.S. MFC has nothing to do with your problems.
In your simple Win32 project you have one main file that keeps including the same item, basically a no-op. To have multiple of the same include in referenced in the same file does not create a new link.
However with your MFC project you put your header file into mainfrm.h. That file is included in several other files in that project not just the mainfrm.cpp. Essentially creating a new link for each of those other files the main header was included in.
1>MainFrm.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>FileView.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>ClassView.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>OutputWnd.obj : error LNK2005: "public: int __thiscall
doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in
MfcTest.obj 1>PropertiesWnd.obj : error LNK2005: "public: int
__thiscall doubleDef::func(void)" (?func#doubleDef##QAEHXZ) already defined in MfcTest.obj
Take a look at that output. You can see each of the other components that thinks it has that object.
To put it another way your original statement of why does it work for one way and not the other is because the complexity of the second example (MFC) actually includes that header all over the place. If you only want it used by the main form then include it in the cpp for it.
This was already answered before, here is more detailed explanation:
You cannot define a function more than once, unless it is inline
You cannot declare a function more than once in the same file.
You do need to declare functions and classes multiple times if they are referenced in multiple .cpp files.
#pragma once prevents multiple declarations in the same file. It will not prevent multiple declarations in different files. Multiple declarations is exactly what you want and it is why you are including the files in multiple .cpp files in the first place.
class N1 {
public:
//Declaration
//Multiple .cpp files need to know about this class and its members
int foo();
};
//Definition
//should be done once. This should go to .cpp file
int N1::foo() {
return 1;
}
In the above example, compile will work fine in multiple .cpp file. The compile routine does not notice multiple definitions. But the linker notices multiple definitions and complains. You have to move the definition to .cpp file or use inline functions.
class N2
{
public:
int foo();
};
inline int N2::foo()
{ //valid, even if it is repeated in different files
return 1;
}
class N3
{
public:
int foo() //always valid
{
return 1;
}
};

can't use separate function files in eclipse

I am trying to declare the functions in separate files. In the code given below, my main() is defined in main.cpp and the int addition(int x, int y) is defined
in an another file named function.cpp.
My code:
main.cpp
#include "function.cpp"
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 15;
int sum = addition(a,b);
cout<<"\nSum = "<<sum<<"\n";
return 0;
}
fucntion.cpp
int addition(int x, int y)
{
int sum = x + y;
return sum;
}
But by using the above cod in Eclipse i am getting the following error. On the other hand, if i compile the code manually using make
through the linux terminal then, the same got works.
ERROR:
/home/eclipse_workspace/multiFiles/Debug/../funtion.cpp:9: multiple definition of `addition(int, int)'
./funtion.o:/home/eclipse_workspace/multiFiles/Debug/../funtion.cpp:9: first defined here
collect2: ld returned 1 exit status.
First of all it is not recommended to include .cpp files. You should create header (.h) with declarations, put implementations to .cpp, like now and wherever you need to use it just include.h . You should also read about avoiding multiple includes by adding #ifndef/#define/#endif.
Update:
#include works in pre compiling phase and more or less it means "paste here what you have in file ...". So it copies function from one file and pastes to main file then compiles it. After this it compiles also cpp file with your function - also ok. Now comes linking: because of previous steps and copy-paste it has two definitions (actually two symbols) which has same name - that is causing the error and that's why we have headers :)
First create a header file, for example Addition.h and declare the function name inside it. Then make a file Addition.cpp and write the addition function implementation and then include the Addition.h in your main.cpp file.
The concept of using a header file is that you can use it anywhere else and is not limited to your main.cpp program file.
So, in short
Addition.h
class Addition { public:
int addition(int a , int b); //function declaration
private: int result_; };
then in Addition.cpp
#include Addition.h
int Addition::addition(int x, int y) {
// function implementation
}
in main.cpp
#include <Addition.h>
int main()
{ int a=3, b=4, sum=0;
Addition objAdd; //creation of object for class Addition
sum = objAdd.addition(a,b);
}
Hope this helps in structuring your code.

error LNK2005: "int __cdecl number(void)" (?number##YAHXZ) already defined in functions.obj

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?
You are having linking issues.
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.
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.
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.