It is my understanding that C has makefiles and include statements so you don’t have singular monster size files and that you should functionally decompose your code. Therefore, if I’m right, I should be able to make functional calls across .c files if I do my headers and makes correctly.
I’m trying to do that but unfortunately I am getting an error.
The files have the following contents:
File 1)test.c:
#include<stdio.h>
#include"suc.h"
main()
{
printf("Hello World\n\n");
printf("This is the number: %d \n\n", suc(6));
}
File 2)makefile:
CC=gcc
CFLAGS=-c -Wall
test: suc.o
$(CC) -Wall -o test test.c
suc.o: suc.c
$(CC) $(CFLAGS) suc.c
File 3)suc.h
#ifndef SUC_H_GUARD
#define SUC_H_GUARD
// returns the successor of i (i+1)
int suc(int i);
#endif
File 4)suc.c
#include "suc.h"
int suc(int i)
{
return i + 1;
}
When I make (make -B) the top I get:
gcc -c -Wall suc.c
gcc -Wall -o test test.c
test.c:7: warning: return type defaults to 'int'
/tmp/cc/7w7qCJ.o: In function 'main':
test.c: (.text+0x1d): undefined reference to 'suc'
collect2: ld returned 1 exit status
make: *** [test] Error 1
However:
Both produce the expected results:
A) This single file program works ok!
#include<stdio.h>
main()
{
printf("Hello World\n\n");
printf("This is the number: %d \n\n", suc(6));
}
int suc(int i)
{
return i + 1;
}
B) All the files in the original but with the following change to test.c:
#include<stdio.h>
#include"suc.h" //suc() is still defined b/c suc.h is included
main()
{
printf("Hello World\n\n");
printf("This is the number: %d \n\n", 4); //HERE! -> no function call
}
Help, please and thank you!
I don’t quite understand what the error messages are trying to tell me.
You need to separately compile the source files to their object files and then link the object file to get the executable
test.So you need:
where
<tab>is a tab.The problem in your current makefile is here:
which says
testdepends onsuc.oand to gettestyou need to do:but look at that compile/link line, it does not include any source/object file that has the
sucfunction defined.You can add a
suc.oas:But it is considered bad because say you change only
suc.cfile then your makefile will regeneratesuc.oand will also have to regeneratetest, but for regeneratingtestyou are re-compilingtest.ceven thought it was not changed.