C++ External Class Implementation Not Working - c++

I am trying to implement my own 'User' class from an external C++ file.
Therefore, I created a User.h, User.cpp and main.cpp file which are all in the same directory. Here you can see the source code of each file:
./User.h
#include <string>
class User {
public:
User(std::string username, std::string password);
std::string getPassword();
std::string username;
private:
std::string password;
};
./User.cpp
#include "User.h"
User::User(std::string username, std::string password) {
this -> username = username;
this -> password = password;
}
std::string User::getPassword() {
return password;
}
./main.cpp
#include <iostream>
#include "User.h"
int main() {
User eve("Eve3033", "Pass1234");
std::cout << eve.getPassword();
return 0;
}
The g++ compiler error:
undefined reference to `User::User(std::\__cxx11::basic_string\<char, std::char_traits\<char\>, std::allocator\<char\> \>, std::\__cxx11::basic_string\<char, std::char_traits\<char\>, std::allocator\<char\> \>)'
C:\\Users\\wise-\\AppData\\Local\\Temp\\ccQgLvm9.o:main.cpp:(.text+0xb8): undefined reference to `User::getPassword[abi:cxx11]()' collect2.exe: error: ld returned 1 exit status
I tried to remove the std::string User::getPassword() method, which didn't result in any compiling errors. The construction of the User eve("Eve3033", "Pass1234") instance was also successfull and I was able to access the public std::string username attribute.
However, when I tried to implement the std::string User::getPassword() method to also access the private std:string password attribute, g++ returned the same error.
I searched for the error online and found the following links:
Undefined reference to Class::Method()
Undefined Reference to Class::Function() in C++
How to fix undefined reference in C++
I hope you have any ideas on that problem :)

Your error must be due to a syntax error or missing file in your command. Compiling this code in VS works just fine, and has the expected output. Make sure you have: g++ main.cpp user.cpp
If you need more context and examples, see here.

Related

Undefined Reference to [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
This is the input to g++ and the resulting error messages.
$ g++ main.cpp -o keyLogger
/tmp/ccvwRl3A.o:main.cpp:(.text+0x93): undefined reference to `SaveFeatures::SaveFeatures(std::string)'
/tmp/ccvwRl3A.o:main.cpp:(.text+0x93): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `SaveFeatures::SaveFeatures(std::string)'
/tmp/ccvwRl3A.o:main.cpp:(.text+0xbf): undefined reference to `SaveFeatures::save(std::string)'
/tmp/ccvwRl3A.o:main.cpp:(.text+0xbf): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `SaveFeatures::save(std::string)'
collect2: error: ld returned 1 exit status
I've checked and rechecked my syntax for the .h and .cpp for SaveFeatures class but havent been able to find an error. Any help would be welcome.
Main.cpp
#include <string>
#include "SaveFeatures.h"
using namespace std;
int main(){
string fileName="saveTest.text";
string saveContent="this is a test";
SaveFeatures saveFeatures(fileName);
saveFeatures.save(saveContent);
}
SaveFeature.cpp
#include "SaveFeatures.h"
#include <string>
using namespace std;
SaveFeatures::SaveFeatures(string fileName){
setFileName(fileName);
}
void SaveFeatures::setFileName(string fileName){
if(fileName!=NULL){
this.fileName=fileName;
}
}
bool SaveFeatures::save(string content){
if(fileName==NULL)return false;
if (content==NULL)return false;
FILE *file;
file=fopen(fileName,"a");
if(file!=NULL){
fputs(content,file);
}
return true;
}
string SaveFeatures::getFileName(){
return fileName;
}
SaveFeatures.h
#ifndef SAVEFEATURES_H
#define SAVEFEATURES_H
#include <string>
using namespace std;
class SaveFeatures{
public:
SaveFeatures(string fileName);
void setFileName(string fileName);
string getFileName();
bool save(string content);
private:
string fileName;
//need to make a method to determine if the fileName has file extension
};
#endif
You will need to specify all the needed source files for your executable.
g++ main.cpp SaveFeature.cpp -o keyLogger

Undefined Reference using KDevelop 4.4.1

I'm a beginner with C++. I wrote the following:
// GradeBook.h
#include <iostream>
#include <string>
using namespace std;
class GradeBook {
public:
GradeBook(string); // constructor that initializes courseName
void setCourseName(string); // function that sets the course name
string getCourseName(); // function that gets the course name
void displayMessage(); // function that displays a welcome message
private:
string courseName; // course name for this GradeBook
};
// GradeBook.cpp
#include <iostream>
#include "GradeBook.h"
using namespace std;
GradeBook::GradeBook(string name)
{
setCourseName(name);
}
void GradeBook::setCourseName(string name)
{
courseName = name;
}
string GradeBook::getCourseName()
{
return courseName;
}
void GradeBook::displayMessage()
{
cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl;
}
// main.cpp
#include <iostream>
#include "GradeBook.h"
using namespace std;
int main()
{
GradeBook gradeBook1("CS101 Introduction to C++ Programming");
GradeBook gradeBook2("CS102 Data Structures in C++");
cout << "gradeBook1 created for course: " << gradeBook1.getCourseName()
<< "\ngradeBook2 created for course: " << gradeBook2.getCourseName()
<< endl;
}
I am using KDevelop 4.4.1, then I proceed to execute my main.cpp and I got:
/home/brallan/projects/Hola/build> make
Linking CXX executable hola
CMakeFiles/hola.dir/main.o: In function main':
/home/brallan/projects/Hola/main.cpp:8: undefined reference to GradeBook::GradeBook(std::string)'
/home/brallan/projects/Hola/main.cpp:9: undefined reference to GradeBook::GradeBook(std::string)'
/home/brallan/projects/Hola/main.cpp:12: undefined reference to GradeBook::getCourseName()'
/home/brallan/projects/Hola/main.cpp:11: undefined reference to GradeBook::getCourseName()'
collect2: error: ld returned 1 exit status
make[2]: [hola] Error 1
make[1]: [CMakeFiles/hola.dir/all] Error 2
make: [all] Error 2
Failed
If I run the same code from Eclipse Juno CDT, it return me:
gradeBook1 created for course: CS101 Introduction to C++ Programming
gradeBook2 created for course: CS102 Data Structures in C++
Can anyone help me to run it from KDevelop?
UPDATE: Based on the comments, KDevelop isn't compiling other files in the project :s
I guess this is the problem to be solved.
First, add the line #error (or any other syntax error) to the end of GradeBook.cpp. Ensure you get a compilation error for that line when you try to build it. If not, check spelling and capitalization of the file reference from the project or makefile.
If you do get a syntax error, or if you don't but you can't figure out why the file isn't being referenced, try this next: Remove the #error from GradeBook.cpp, and add #include "GradeBook.cpp" to the end of main.cpp. This serves two purposes: It get you going (should now be able to build and run) and it helps narrow the problem (if it works, you know the problem is with referencing GradeGook.cpp, rather than with its contents).
It seems you are not compiling GradeBook.cpp
In the project folder, there is a file called CMakeList.txt and on it are the files that are part of the project. I tried to add the file GradeBook.cpp to add_executable line, but still did not work. However, when I replaced the file names in lower case, and turn modify the line that I described, everything worked properly. I'm not sure what is the mistake if the file name has no upper or similarly if I add it to this list exactly as it is called.
Then, I renamed files gradebook.h and gradebook.cpp and added gradebook.cpp to add_executable line.

Linking error in dereferencing static variable

(I've failed to find any similar question... so, I hope you can help me)
In a program in C++ that I'm developing, I have a class that simulates a thread. I'll call it "Test" here. In it, I have an static map (std::map, from STL) that in which I store some semaphores (because I need all of the threads to have access to the same semaphores). (I think it is not worth to explain why I'm using a map, instead of a vector, but I believe this shouldn't be a problem)
To "get" this static variable, I created a getMutexHash() function, that returns a pointer to the static map. But, for some reason, after compiling, I'm getting a linker error when trying to return a this pointer.
The following code exemplifies the problem:
// MAIN.CPP
#include "Test.h"
int main ()
{
Test test;
map<int, pthread_mutex_t>* mutexHash = test.getMutexHash();
return 0;
}
// TEST.H
#include <map>
#include <pthread.h>
using namespace std;
class Test
{
public:
map<int, pthread_mutex_t>* getMutexHash();
private:
static map<int, pthread_mutex_t> mutexHash;
};
// TEST.CPP
#include "Test.h"
map<int, pthread_mutex_t>* Test::getMutexHash()
{
return &mutexHash;
}
When compiling, I get no error nor warnings; but when linking, I receive this error:
Test.o: In function `Test::getMutexHash()':
Test.cpp:(.text+0x9): undefined reference to `Test::mutexHash'
collect2: ld returned 1 exit status
Can someone help me?
You've declared that mutexHash exists, but haven't defined it. You need to add a definition to test.cpp:
map<int, pthread_mutex_t> Test::mutexHash;

undefined reference to a class ERROR

I am working in c++ /ubuntu.
I have:
libr.hpp
#ifndef LIBR
#define LIBR
#include <string>
using namespace std;
class name
{
public:
name();
~name();
std::string my_name;
std::string method (std::string s);
};
#endif
and
libr.cpp
#include <iostream>
#include <string>
#include <stdlib.h>
#include "libr.hpp"
using namespace std;
name::name()
{
}
std::string name::method(std::string s)
{
return ("YOUR NAME IS: "+s);
}
From these two I've created a libr.a.
In test.cpp:
#include <iostream>
#include <string>
#include <stdlib.h>
#include "libr.hpp"
using namespace std;
int main()
{
name *n = new name();
n->my_name="jack";
cout<<n->method(n->my_name)<<endl;
return 0;
}
I compile with g++ and libr.a. I have an error: "name::name() undefined reference", why?
I would like to mention that I've added in qt creator at qmake the .a. When I compile, I have the error. How can I solve it?
This is a linker error, not a compiler error. It means that you have called but you have not defined the constructor. Your allocation name *n = new name(); calls the constructor.
Since you defined the constructor in your libr.cpp, what this means is that this compilation unit is not making its way into your executable. You mentioned that you are compiling with libr.a. When you compile your libr.cpp the result is a .o file, not a .a file.
You are not linking libr.o into your executable.
What are the steps you're using to compile your "project"?
I performed the following steps and managed to build it with warnings/errors.
g++ -Wall -c libr.cpp
ar -cvq libr.a libr.o
g++ -Wall -o libr main.cpp libr.a
One last thing, if I change the order off the last command, like
g++ -Wall -o libr libr.a main.cpp
I get the following error:
Undefined first referenced
symbol in file
name::name() /tmp/cc4Ro1ZM.o
name::method(std::basic_string<char, std::char_traits<char>, std::allocator<char
> >)/tmp/cc4Ro1ZM.o
ld: fatal: Symbol referencing errors. No output written to libr
collect2: ld returned 1 exit status
in fact , you needn't define the destructor yourself because the default destructor will be used when the class calling is over.
and in the VS2008,it's all right!

eclipse C++ add reference undefined reference to method error

I'm new to C++ and ecplice and they are definitely giving my a hard time :)
I'm tring to write simple application that includes main project with refernces to other project
i wrote the following file in shared project:
#ifndef MANAGEDLOG_H_
#define MANAGEDLOG_H_
#include string
#include iostream
#include fstream
using namespace std;
class ManagedLog
{
ofstream _fileStream;
public :
ManagedLog::ManagedLog(string path);
ManagedLog::~ManagedLog();
void ManagedLog::WriteInfoLog(string message,string stackTrace);
};
#endif /* MANAGEDLOG_H_ */
/*
* ManagedLog.cpp
*
* Created on: 18/06/2010
* Author: Eran
*/
#include "ManagedLog.h"
#include iostream
#include fstream
ManagedLog::ManagedLog(string path)
{
_path=path;
}
ManagedLog::~ManagedLog()
{
}
void ManagedLog:: WriteInfoLog(string message,string stackTrace)
{
ofstream myfile;
myfile.open("Eample.txt",ios::app);
myfile.close();
}
and run it in simple hellow world project:
#include "ManagedLog.h"
#include
using namespace std;
int main() {
ManagedLog * log = new ManagedLog("path");
log->WriteInfoLog("test","RunLog/Main");
cout
but I'm getting this error:
*** Build of configuration Debug for project RunLog ****
**** Internal Builder is used for build ****
g++ -ID:\EclipseWorkSpace\LogManager -O0 -g3 -Wall -c -fmessage-length=0 -osrc\RunLog.o ..\src\RunLog.cpp
g++ -LD:\EclipseWorkSpace\LogManager\Release -oRunLog.exe src\RunLog.o
src\RunLog.o: In function `main':
D:/EclipseWorkSpace/RunLog/Debug/../src/RunLog.cpp:13: undefined reference to `ManagedLog::ManagedLog(std::string)'
D:/EclipseWorkSpace/RunLog/Debug/../src/RunLog.cpp:14: undefined reference to `ManagedLog::WriteInfoLog(std::string, std::string)'
collect2: ld returned 1 exit status
Build error occurred, build is stopped
Time consumed: 574 ms.
I added #include "ManagedLog.cpp" and the code work just fine but i guess this is not the right way to do it i read a lot about it but found no answer that i can impliment since i don't understad the term is the reanswers can anybody please help me with the right way to point to other project or dll in this environment?
thanks
Eran
You're not building ManagedLog.cpp. Your compile sequence should look something like this example (simplified for clarity):
compile RunLog.c into RunLog.o
compile ManagedLog.c into ManagedLog.o
link RunLog.o and ManagedLog.o into RunLog.exe
Steps 1 & 2 could be in the other order if you like.