How to build a program with multiple files whith inter files function calls with makefile in C

I am struggling with building a program with multiple files whith inter files function calls with makefile in C. Let’s say that I have a main file which call a function call_print_hello() declared in a header file fdeclar_macros.h and written in the file script1.c. The function call_print_hello() itself calls another function print_hello() also declared in fdeclar_macros.h and written in script2.c. I have also a makefile but when I run it I get the following error message:

gcc  -g -Wall -c main.c
gcc  -g -Wall -c script1.c
gcc  -o main main.o script1.o
Undefined symbols for architecture x86_64:
  "_call_print_hello", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [main] Error 1

Here are the content of the files:


CC = gcc 
CFLAGS = -g -Wall

main: main.o script1.o
    $(CC) -o main main.o script1.o 

main.o: main.c fdeclar_macros.h
    $(CC) $(CFLAGS) -c main.c

script2.o: script2.c fdeclar_macros.h
    $(CC) $(CFLAGS) -c script2.c

script1.o: script1.c fdeclar_macros.h
    $(CC) $(CFLAGS) -c script1.c

run: main

    $(RM) -rf justify *.dSYM *.o


#include "fdeclar_macros.h"

int main(){
  return 0;


#define NUMBER 3

void print_hello();
void call_print_hello();


#include <stdio.h>
#include "fdeclar_macros.h"

void print_hello(){
  printf("hello %d\n", NUMBER);


#include "fdeclar_macros.h"

void call_print_hello(){

>Solution :

The make target for the main executable does not contain a dependency on script2.o and the rule to build main does not link script2.o into the main executable either.

So the linker tries to build an executable with the content of script2.o missing, but as that content is required, linking fails.

Leave a Reply