Learner
Learner

Reputation: 141

Makefile separate directories

It really takes a long time to read the make and gcc manual. Since I just need some basic function of them, I want to learn them quickly.

The project directory is like the following.

CWD
|----Source----1.cpp
|----Header----1.h
|----Object----1.o
|----Makefile

There are three directories and one Makefile in Current Working Directories, and "1.cpp" includes "1.h". I want to use Makefile which is in the CWD to compile the project such that the object output is in Object directory.

This is simplified version of the problem I have now. Since it is relatively hard to begin from scratch, could anyone help me to write a Makefile for this simple problem? And I will try to learn from it and solve my own problem. Or could anyone suggests which parts of make and gcc I need to learn to solve this problem.

Thanks in advance.

Upvotes: 1

Views: 149

Answers (1)

Beta
Beta

Reputation: 99084

This will be enough to compile the source and produce the object:

Object/1.o: Source/1.cpp Header/1.h
    $(CXX) -c Source/1.cpp -IHeader -o Object/1.o

If you want to build an executable, maybe called "one", add another rule above that:

one: Object/1.o
    $(CXX) Object/1.o -o one

Object/1.o: Source/1.cpp Header/1.h
    $(CXX) -c Source/1.cpp -IHeader -o Object/1.o

To clean things up a little, use automatic variables:

one: Object/1.o
    $(CXX) $^ -o $@

Object/1.o: Source/1.cpp Header/1.h
    $(CXX) -c $< -IHeader -o $@

And if you want to make the second rule more general, so that it can handle more objects you can turn the second rule into a pattern rule and separate the header dependency of 1.o:

one: Object/1.o
    $(CXX) $^ -o $@

Object/1.o: Header/1.h

Object/%.o: Source/%.cpp
    $(CXX) -c $< -IHeader -o $@

And of course there is a lot more you can do, when you're ready.

Upvotes: 2

Related Questions