Michael LeVan
Michael LeVan

Reputation: 548

Set Target Location for Makefile

I am compiling a C project on AIX with the GNU make tool and want the .o files to be installed in the build directory under my project. However, the current configuration puts the .o's in the project directory where the makefile is located. The directory structure is:

project

The source files are in src/.

The makefile contains the following text:

src = /PATHTO/project/src/
build = /PATHTO/project/build/

objects = $(build)config.o #(...)

$(build)main : $(objects)
   cc -o main $(objects)

$(build)config.o : $(src)config.c $(src)config.h
   cc -c $(src)config.c

This makefile works but config.o and main are both placed under project instead of under project/build.

Thank you.

Upvotes: 1

Views: 3350

Answers (2)

user3629249
user3629249

Reputation: 16540

the correction is simple

The location of the resulting files needs to be specifically defined.

That location is defined by using the '-o' parameter

so use:

src = /PATHTO/project/src/
build = /PATHTO/project/build/

objects = $(build)config.o #(...)

$(build)main : $(objects)
    CC -o $@ $(objects) 

$(build)config.o : $(src)config.c $(src)config.h
    CC  -c $< -o $@ -I.

Upvotes: 1

CristiFati
CristiFati

Reputation: 41137

There are 2 things:

  • when building main the folder is not specified; it defaults to current directory(/PATHTO/project)
  • when compiling config.c the output is not specified; it also defaults to current directory

Now why it works i'm not sure because it should not find $(build)config.o (unless you copied it there manually).

To get things working modify your rules to:

$(build)main : $(objects)
    cc -o $@ $?

$(build)config.o : $(src)config.c $(src)config.h
    cc -c -o $@ $<
  • $@ is the rule's target
  • $? are the target's dependents
  • $< is the first dependent (note that this is not to be used when the target has multiple .c dependents

Of course things can be taken further:

  • define a clean target
  • use pattern rules

as described here.

Upvotes: 1

Related Questions