0

I receive the following error when I try to compile three c++ files with g++ main.cpp. If I combine them in one file, it works.

main.cpp:(.text+0x10): undefined reference to `Time::Time()'

Time.cpp

#include <iostream>
#include "Time.h"
using namespace std;

Time::Time()
{
    a=5;
}

Time.h

#ifndef TIME_H
#define TIME_H

class Time {

public:
Time();
private:
int a;
};
#endif

main.cpp

#include <iostream>
#include "Time.h" 
using namespace std;


int main()
{
    Time t;
}
phuclv
  • 37,963
  • 15
  • 156
  • 475
Dave
  • 3
  • 1
  • You will need to tell the compiler to compile Time.cpp as well. For example: `g++ main.cpp Time.cpp -o main` – aschepler Mar 17 '17 at 02:24
  • Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – 1201ProgramAlarm Mar 17 '17 at 02:45

1 Answers1

3

You need to compile all the CPP files because each one is a separate compilation unit

g++ main.cpp Time.cpp -o main

For more information about that read

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • is there a shortcut? what about if I have more than 100 files? – Dave Mar 17 '17 at 02:31
  • 2
    if you have that many files then you must create a [makefile](https://en.wikipedia.org/wiki/Makefile), otherwise you'll end up compiling a file again and again. In MSVC or some other IDEs just create a new solution/project and the IDE will handle the compilation for you – phuclv Mar 17 '17 at 02:34
  • You could use shell expansion, e.g. `g++ *.cpp -o main` – M.M Mar 17 '17 at 03:03