0
votes

I ran into an issue with make. I have 3 files.

main.cpp | src/Math/Vector2.cpp | src/Math/Vector2.hpp

Here is my MakeFile:

main: vector2.o main.o
    g++ -o main.o vector2.o

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

vector2.o: src/Math/Vector2.cpp src/Math/Vector2.hpp
    g++ -o vector2.o src/Math/Vector2.cpp -lm -c

When i copy these commands manually , it compiles perfectly fine. However $make main returns

g++     main.cpp   -o main
/tmp/ccnRZ4UD.o: In function `main':
main.cpp:(.text+0x42): undefined reference to ` 
phy2d::Maths::Vector2f::Vector2f(double, double)'
main.cpp:(.text+0x66): undefined reference to ` 
phy2d::Maths::Vector2f::Vector2f(double, double)'
main.cpp:(.text+0x79): undefined reference to ` 
phy2d::Maths::Vector2f::distance(phy2d::Maths::Vector2f const&) 
const'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'main' failed
make: *** [main] Error 1

Any ideas??

1
try running make --dry-run, this will show you exact commands make executes. Then you should be able to find in which step this error occurs and why...Kamil S Jaron
g++ main.cpp -o main That is not the same as what is in the Makefile. Makfile has extra -c.kaylum
Anyway, your makefile looks wrong. It does not produce the main executable. There are two targets which both produce main.okaylum

1 Answers

3
votes

There's no way that the makefile you provide will give the output you show.

In your comment you said Here is my MakeFile. Note that make will not read a file named MakeFile. It will read files named Makefile and makefile, but if you're using a case-sensitive filesystem then one explanation for the behavior you're seeing is that you've used MakeFile for your makefile name and make can't find it.

Or, you could have simply been imprecise in your question, but then this can't be the makefile that make is using for some other reason.

Also, there are numerous errors with your makefile:

  1. You have two different targets main and main.o where the command generates the same file, -o main.o
  2. You are adding libraries -lm to your compile line for vector2.o; libraries should go on the link line.

In general you should be using automatic variables to make sure your makefile is agreeing with what you want it to do.

Here's a reasonable makefile for your situation:

CXX = g++

main: vector2.o main.o
        $(CXX) -o $@ $^ -lm

main.o: main.cpp
        $(CXX) -c -o $@ $<

vector2.o: src/Math/Vector2.cpp src/Math/Vector2.hpp
        $(CXX) -c -o $@ $<