Makefile assistance

I'm having issue compile with make using a Makefile and g++. I have a simple header and source file for a class along with main. I'm unable to get it to compile with the error,

g++ -o Hello.o hello.cpp
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/8/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
make: *** [Makefile:5: Hello.o] Error 1


Here are the files

hello.hpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef HELLO_HPP
#define HELLO_HPP

#include <iostream>

class Hello
{
public:
    Hello(){}

    void PrintHello();
};

#endif 



hello.cpp

1
2
3
4
5
6
#include "hello.hpp"

void Hello::PrintHello()
{
    std::cout << "Hello world" << std::endl;
}



main.cpp

1
2
3
4
5
6
7
8
9
#include "hello.hpp"

int main()
{
    Hello h;
    h.PrintHello();

    return 0;
}



Makefile

1
2
3
4
5
Main.o: main.cpp Hello.o
	g++ -o Main.o main.cpp

Hello.o: hello.cpp hello.hpp
	g++ -o Hello.o hello.cpp



I'm just confused about how g++ links and compiles files, having always used an IDE. I'd like to be able to control that myself and am having a difficult time understanding how it all works.

Any help is appreciated.
Last edited on
You missed the -c argument to produce an object file. Without it gcc tries to link a complete executable. You also need one more makefile rule to link both object files into an executable.
Would you mind providing an example?

Edit: Just did a test run, with your advice and works perfectly. No need for an example. Thanks for the quick response.

Makefile is now:

1
2
3
4
5
6
7
8
Practice.o: Main.o Hello.o
	g++ -o Practice.o Main.o Hello.o

Main.o: main.cpp Hello.o
	g++ -c -o Main.o main.cpp

Hello.o: hello.cpp hello.hpp
	g++ -c -o Hello.o hello.cpp
Last edited on
Topic archived. No new replies allowed.