Michael Jones
Michael Jones

Reputation: 15

Why while using makefile I receive undefined reference error?

I created the following makefile:

assembler: main.o first_pass.o second_pass.o helpers.o data_array.o symbol_table.o
            gcc -Wall -ansi -pedantic main.o first_pass.o second_pass.o helpers.o data_array.o symbol_table.o -o assembler
main.o:         main.c header.h
                gcc -Wall -ansi -pedantic main.c -o main.o
first_pass.o:   first_pass.c header.h
                gcc -Wall -ansi -pedantic first_pass.c -o first_pass.o
second_pass.o:  second_pass.c header.h
                gcc -Wall -ansi -pedantic second_pass.c -o second_pass.o
helpers.o:      helpers.c header.h data.h
                gcc -Wall -ansi -pedantic helpers.c -o helpers.o
data_array.o:   data_array.c header.h data.h
                gcc -Wall -ansi -pedantic data_array.c -o data_array.o
symbol_table.o: symbol_table.c header.h data.h
                gcc -Wall -ansi -pedantic symbol_table.c -o symbol_table.o

In my 'main.c' file I have #include "header.h". Where in 'header.h' I have the declarations of all the functions. But I receive the following error:

gcc -Wall -ansi -pedantic main.c -o main.o
/tmp/cc3dP7hx.o: In function `main':
main.c:(.text+0x257): undefined reference to `first_pass`
main.c:(.text+0x2e4): undefined reference to `second_pass'
main.c:(.text+0x37f): undefined reference to build_obj_file
main.c:(.text+0x3a9): undefined reference to build_ent_file
main.c:(.text+0x427): undefined reference to free_all_data
main.c:(.text+0x436): undefined reference to free_all_symbols
main.c:(.text+0x44d): undefined reference to free_all_words
collect2: error: ld returned 1 exit status
makefile:4: recipe for target 'main.o' failed
make: *** [main.o] Error 1

Upvotes: 0

Views: 857

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

The problem is that your command doesn't create object files, but attempt to build executable programs:

gcc -Wall -ansi -pedantic main.c -o main.o

You need the -c option to create object files:

gcc -Wall -pedantic main.c -c -o main.o

A better idea would be to rely on the make implicit rules so you don't have to explicitly list all commands:

CC = gcc
LD = gcc
CFLAGS = -Wall -pedantic
LDFLAGS =

assembler: main.o first_pass.o second_pass.o helpers.o data_array.o symbol_table.o

You might want to add rules for the header-file dependencies, or figure out some way to auto-generate them (it's possible). Other than that the above Makefile should be enough to build all object files and then link them together into the assembler executable program.

Note that I have removed the -ansi flag, as it's mostly obsolete these days.

Upvotes: 3

Related Questions