Tutorial: Quick guide to using make and Makefile
bar.h
#ifndef __myproject_h__
#define __myproject_h__
int getX();
#endif
bar.cpp
#include <iostream>
#include "bar.h"
using namespace std;
int getX() {
cout << "getX accessed" << endl;
return 10;
}
foo.cpp
#include <iostream>
#include "bar.h"
using namespace std;
int main() {
cout << "Hello World!" << endl;
int x = getX();
cout << "Value of x: " << x << endl;
return 0;
}
Makefile
CXX = g++
CFLAGS = -Wall
LDFLAGS =
OBJFILES = foo.o bar.o
TARGET = foobar
all: $(TARGET)
$(TARGET): $(OBJFILES)
<TAB>$(CXX) $(CFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS)
.PHONY: clean
clean:
<TAB>rm -f $(OBJFILES) $(TARGET) *~
Important: Replace <TAB> by an actual tab (spaces won’t do)
Steps:
- Store all these files in the same directory,
cd
into that directory - Run
make
-
Run
./foobar
The expected output is:Hello World!
getX accessed
Value of x: 10 - To get rid of all the files generated by make, run
make clean
Useful notes:
<*.h>
is used for standard libraries,"*.h"
is used for header files defined in the project.#ifndef
is needed as the header file is called multiple times. This prevents multiple declarations ofgetX()
which would otherwise cause an error.- You can’t have more than 1
main()
while building a single target.
Similar quick guide for cmake and CMakeLists.txt