1

I have a doubt on compiling C code which is distributed under different source folders. My project structure is as follows

root directory---> Project
sub-directory--> include => add.h sub.h
sub-directory--> source => add.c sub.c
sub-directory--> src => main.c crc.c spi.c

How do I write a simple makefile to compile and link the sources in different directories to create an executable file?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Gibson Justian
  • 107
  • 2
  • 9

3 Answers3

2

You can just list paths to all your source files in a Makefile:

SOURCES=\
    src/main.c \
    src/crc.c \
    src/spi.c \
    sources/add.c \
    sources/sub.c
0

Here is a fundamental makefile sample you could use. Clean is suggested to remove the compiled executables

 # ------------------------------------------------
 # Generic Makefile
 #
 # Author: yanick.rochon@gmail.com
 # Date  : 2010-11-05
 #
 # Changelog :
 #   0.01 - first version
 # ------------------------------------------------

 # project name (generate executable with this name)
 TARGET   = projectname

 CC       = gcc -std=c99 -c
 # compiling flags here
 CFLAGS   = -Wall -I.

 LINKER   = gcc -o
 # linking flags here
 LFLAGS   = -Wall

 SOURCES  := $(wildcard *.c)
 INCLUDES := $(wildcard *.h)
 OBJECTS  := $(SOURCES:.c=*.o)
 rm       = rm -f

 $(TARGET): obj
 @$(LINKER) $(TARGET) $(LFLAGS) $(OBJECTS)
 @echo "Linking complete!"

 obj: $(SOURCES) $(INCLUDES)
 @$(CC) $(CFLAGS) $(SOURCES)
 @echo "Compilation complete!"

 clean:
      @$(rm) $(TARGET) $(OBJECTS)
      @echo "Cleanup complete!"

This would compile all the files in a directory with a particular file extension.

P.S: If you name the file as "makefile", all you have to do to execute the file is to write "./make" on the linux terminal prompt.

bit_by_bit
  • 337
  • 2
  • 14
0

It seems that you will have to place a separate makefile in each sub-directory and recursively call each once starting from the root directory. Gnu mentions the recursive makefile here: https://www.gnu.org/software/make/manual/html_node/Recursion.html

There may, however, be reasons not to do such a thing. Some specific examples are mentioned here: http://miller.emu.id.au/pmiller/books/rmch/

You also may choose to hardcode the paths into your makefile like this user did: Makefile: Compiling from directory to another directory

Community
  • 1
  • 1
ghrs
  • 31
  • 5