Skip to content
Advertisement

Undefined reference error while compiling

I’m trying to compile a project that has multiple *.c files and *.h file when I type the following command:

$gcc -c -I ../hdr main.c gestic.c menu.c

the hdr folder is where the *.h files are located, the .o files are created but when I try to link them using the command:

$gcc -o main.o gestic.o menu.o

I see errors

gestic.c:(.text+0x..): undefined reference to functions that are declared in *.h files

Advertisement

Answer

$gcc -Wall -c -I../hdr -o main.o main.c
$gcc -Wall -c -I../hdr -o menu.o menu.c
$gcc -Wall -c -I../hdr -o gestic.o gestic.c
$gcc -Wall -o myprogram main.o menu.o gestic.o

Using a Makefile is very common for this task

example (untested) Makefile:

CC=gcc
CFLAGS=-Wall -I../hdr 

all: myprogram

myprogram: main.o menu.o gestic.o
 $(CC) -o $@ $^

gestic.o: gestic.c
 $(CC) $(CFLAGS) -c -o $@ $<

main.o: main.c
 $(CC) $(CFLAGS) -c -o $@ $<

menu.o: menu.c
 $(CC) $(CFLAGS) -c -o $@ $<
Advertisement