Read .h files and .c files from different directories using makefile

advertisements

I'm trying to compile a program called um from a current folder with um.c and include some external implementations. The .h files are in one directory but the .c files implementing these .h files are in a different directory. Below is my makefile. It seems that the compiler knows where to look for the .h file. However, the linker fails and produces the error:

ld: symbol(s) not found for architecture x86_64
clang: fatal error: linker command failed with exit code 1

Makefile:

# define the C compiler to use
CC = gcc

# define any compile-time flags
CFLAGS = -g -O -Wall -Wextra -Werror -Wfatal-errors -std=c99 -pedantic

# define any directories containing header files other than /usr/include
INCLUDES = -I/Users/nguyenmanhduc/Documents/C\ library/cii/include

# define library paths in addition to /usr/lib
LFLAGS = -L/Users/nguyenmanhduc/Documents/C\ library/cii/src

# define any libraries to link into executable:
LIBS = -lm

# define the C source files
SRCS = um.c

# define the C object files
OBJS = $(SRCS:.c=.o)

# define the executable file
MAIN = um

.PHONY: depend clean

all:    $(MAIN)
    @echo  Simple compiler named um has been compiled

$(MAIN): $(OBJS)
    $(CC) $(CFLAGS) $(INCLUDES) -o $(MAIN) $(OBJS) $(LFLAGS) $(LIBS)

.c.o:
    $(CC) $(CFLAGS) $(INCLUDES) -c $<  -o [email protected]

clean:
    $(RM) *.o *~ $(MAIN)

depend: $(SRCS)
    makedepend $(INCLUDES) $^

This question might seem weird because I have little experience with makefile but is there a way that I can link .h and .c files in different folders using makefile.

Thanks!


The problem here is not that your additional .c files are in different directories: it's that you didn't tell your Makefile that they exist at all!

Here's where you list the source inputs (I guess you didn't see the comment?):

# define the C source files
SRCS = um.c

Add the other .c files whose compiled .os are what you want to link.

For example:

# define the C source files
SRCS = um.c ../wot.c ../hah/lol.c

There is no hard and fast rule but, the way you've constructed this Makefile, those relative paths should resolve just fine.