Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined Reference Compiler Error

Tags:

c++

I think I'm getting close, but I'm having this error I've been banging my head against the wall on for hours. I'm missing something stupid, and I've gone character by character but I can't find it.

The compiler is giving me

main.cpp:16: undefined reference to `translator::translator(std::istream&)'
collect2: error: ld returned 1 exit status

when I try to compile my program. The command I'm using to compile is:

clear && g++ -g -Wall main.cpp -o Pear

The three sections of use are as follows:

main.cpp

int main(int argc, char* argv[])
{

std::ifstream myFile;

myFile.open(argv[1]);

translator example(myFile); 

myFile.close(); 

return 0; 
}

translator.cpp

#include <fstream>
#include <iostream>
#include <string>

#include "translator.h"


translator::translator(std::istream& in)
{   
table1(in);
table2(in);
}

translator.h

#ifndef TRANSLATOR
#define TRANSLATOR

#include <fstream>
#include <iostream>
#include <string>

#include "translationTable.h"


class translator
{
private:

translationTable<std::string, int> table1;

translationTable<int, std::string> table2;

translator(); 

public:

translator(std::istream& in); 

};



#endif

Any ideas? I've tried so much, and I've looked up similar problems, but they all have different sources. Thanks in advance!

like image 377
pgowdy13 Avatar asked Dec 12 '25 13:12

pgowdy13


1 Answers

The command line for g++ needs to include both source files, like this:

g++ -g -Wall main.cpp translator.cpp -o Pear

Otherwise, the compiler has no idea from where to get the implementation of the translator::translator(std::istream&) member function.

*EDIT: * (from the comment)

I thought that basically the use of header files was so that it would know where to get each implementation of the file?

This part is grossly oversimplified, but it should help you get the picture. Recall that the process of producing an executable from C++ sources consists of two major steps - compilation and linking. The g++ program performs them both (it can do just one if you specify -c flags, or pass only .o files).

The compiler and the linker stages of g++ do not "talk" to each other directly. The compiler produces the inputs for the linker, and that's where the communication ends.

Header files are for the compiler. Specifically, they are for the first stage of compilation - the preprocessing. Once the preprocessor has finished, there is no knowledge of where the definitions came from. Even the compiler does not know it, let alone the linker. That is why you need to "help" the linker by supplying all the relevant sources to g++.

like image 165
Sergey Kalinichenko Avatar answered Dec 15 '25 03:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!