ucas
ucas

Reputation: 487

Writing Makefile for c++ program

I have written c++ program on NetBeans, now I want to run it on Linux on command line. How can I write Makefile, what is the logic of writing it?

I have 3 .cpp files and 2 .hpp files.

This is what I have tried to do:

# Makefile

# the C++ compiler
CXX     = g++
CC      = $(CXX)

# options to pass to the compiler
CXXFLAGS = -Wall -ansi -O2 -g
Run: Run.cpp Assessment3.o Student.o
$(CXX) $(CXXFLAGS) Run.cpp Assessment3.o Student.o -o Run

Run: Run.cpp Assessment3.hpp  Assessment3.o Student.o
 $(CXX) $(CXXFLAGS) Run.cpp Assessment3.o Student.o -o Run  

Assessment3.o: Assessment3.cpp Assessment3.hpp
$(CXX) $(CXXFLAGS)  -c Assessment3.cpp

Student.o: Student.cpp Assessment3.o
    $(CXX) $(CXXFLAGS) -c Student.cpp 

It gives me 'missing separator. Stop.' error on command line. It is not saying that this is an error though. Cheers

Upvotes: 0

Views: 1141

Answers (3)

codeling
codeling

Reputation: 11369

The 'missing separator' error usually comes from not using TAB character in front of the commands to execute for a specific target. Try the following:

Run: Run.cpp Assessment3.o Student.o
[TAB] $(CXX) $(CXXFLAGS) Run.cpp Assessment3.o Student.o -o Run

Instead of [TAB], you'll have to insert a tab character of course.

Upvotes: 0

Paul R
Paul R

Reputation: 212929

Assuming you want to build an executable named foo, you can just use a simple makefile which builds everything in one go with just one dependency :

# makefile 

SRCS = a.cpp b.cpp c.cpp

HDRS = a.h b.h

CXXFLAGS = -Wall

foo: $(SRCS) $(HDRS)
    g++ $(CXXFLAGS) $(SRCS) -o $@

EDIT

Alternatively, taking your initial makefile above and fixing a few minor problems:

# Makefile

# the C++ compiler
CXX     = g++
CC      = $(CXX)

# options to pass to the compiler
CXXFLAGS = -Wall -ansi -O2 -g

Run: Run.o Assessment3.o Student.o
    $(CXX) $(CXXFLAGS) Run.o Assessment3.o Student.o -o $@

Run.o: Run.cpp
    $(CXX) $(CXXFLAGS) Run.cpp -o $@  

Assessment3.o: Assessment3.cpp Assessment3.hpp
    $(CXX) $(CXXFLAGS) -c Assessment3.cpp -o $@

Student.o: Student.cpp Student.hpp
    $(CXX) $(CXXFLAGS) -c Student.cpp -o $@

Upvotes: 3

Evan Levesque
Evan Levesque

Reputation: 3203

This can be helpful http://mrbook.org/tutorials/make/ for me I use qMake that is available with QtCreator

Upvotes: 1

Related Questions