loopi
loopi

Reputation: 51

how to create a makefile with several sub-directories

I have one directory and underneath it 4 subdirectories like so:

myDir:
myDir/Part1
myDir/Part2
myDir/Part3
myDir/shared

I want to make an executable that takes files from shared, links it to files in Part2 and puts the executable in myDir.

This is what I tried (only the lines in the makefile that are relevant):

Shared/helper.o:
gcc -ansi -pedantic-errors -c -Wall -Werror -g -o Shared/helper.o Shared/helper.c

and above it in the makefile:

Part2/part2code.o: ../Shared/helper.o
gcc -ansi -pedantic-errors -c -Wall -Werror -g -o Part2/part2code.o Part2/part2code.c

and above it in the makefile:

part2code: Part2/part2code.o  ../Shared/helper.o
gcc -ansi -pedantic-errors -Wall -Werror -g -lm -o part2code Part2/part2code.o  ../Shared/helper.o

(I also tried without the ../ before Shared)

I get this error:

No such file or directory.

help?

Thanks!

Upvotes: 0

Views: 218

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272792

In this context, paths in filenames are all relative to where the makefile is. So e.g. Part2/part2code.o: ../Shared/helper.o is incorrect; it should simply be Part2/part2code.o: Shared/helper.o (and so on). Note also that you've written Shared in your makefile, but you've listed your directory as shared...

Although actually, that's still wrong. Rules such as a: b express that b is a prerequisite of a; i.e. that you cannot make a until you've made b. That is not the case for your object files; they don't depend on each other. Usually, an object file depends purely on its constituent source files (*.c and *.h). So, for example, your rule for part2code.o might be something like:

Part2/part2code.o: Part2/part2code.c
    gcc -ansi -pedantic-errors -c -Wall -Werror -g -o $@ $^

(Note the use of the special variables $@ and $^, which substitute in for the target and the prerequisites, respectively.)

Upvotes: 2

Related Questions