2

I'm trying to build a program which needs 2 source codes. Here is the simplified source codes and a makefile. And I copied some ideas here to write this simple makefile.

But still don't fully understand why I see this error.

[Source code 1 : main.c]

#include <stdio.h>
#include <stdlib.h>

#include "data.h"

int main(void)
{
   test_cfg.a1 = 1;
   printf("test_cfg.a1 = %d\n", test_cfg.a1);

   func();
   return 0;
}

[Source code 2 : func.c]

#include <stdio.h>
#include <stdlib.h>

#include "data.h"

int func(void)
{
   test_cfg.b1 = 12;
   printf("test_cfg.b1 = %d\n", test_cfg.b1);

   return 0;
}

[Header file : data.h]

#ifndef _DATA_H_
#define _DATA_H_

struct {
  int a1;
  int b1;
  int c1;
} test_cfg;

int func(void);
#endif /* end of _DATA_H_ */

[Makefile]

CC = gcc
AR = ar
ARFLAGS = rcs

CFLAGS += -Wall -std=c99

SOURCE=./main.c ./func.c
OBJECTS=$(SOURCE:.c=.o)

all: app_test

app_test:$(OBJECTS)
    $(CC) -o $@ $(OBJECTS)

.c.o:
    $(CC) $(CFLAGS) $<

.PHONY: all clean

clean:
    rm -f *.o app_test

[Output]

$ make
gcc -Wall -std=c99 main.c
/usr/bin/ld: /tmp/ccjahoYC.o: in function `main':
main.c:(.text+0x2f): undefined reference to `func'
collect2: error: ld returned 1 exit status
make: *** [Makefile:16: main.o] Error 1
1
  • 3
    If you want the compiler to generate an object file you have to give the -c option. If you don't specify what kind of result you want, the compiler will try to link the code on the command line into an executable. So in your recipe for .c.o to build an object file you have to use $(CC) -c $(CFLAGS) $< Commented Apr 24, 2024 at 16:58

1 Answer 1

0

Makefile something like

NAME = app_test

CC ?= gcc
CFLAGS += -Wall -std=c99

SOURCE  = main.c func.c
OBJECTS = $(SOURCE:.c=.o)

all: $(NAME)

$(NAME): $(OBJECTS)
    $(CC) -o $@ $(OBJECTS) $(LDFLAGS) $(LIBS)

%.o: %.c data.h
    $(CC) -c -o $@ $(CFLAGS) $<

clean:
    rm -f $(NAME) $(OBJECTS)

to remove type_cfg definition from header, just for example

data.h

#ifndef _DATA_H_
#define _DATA_H_

typedef struct test_cfg {
  int a1;
  int b1;
  int c1;
} t_test_cfg;

extern t_test_cfg test_cfg;

int func(void);

#endif

func.c

#include <stdio.h>

#include "data.h"

t_test_cfg test_cfg;

int func(void) {
   test_cfg.b1 = 12;
   printf("test_cfg.b1 = %d\n", test_cfg.b1);
   return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I was about to post another question about multiple definition error. It seems you explained it. I also have the same idea. But somehow I saw it was compiled at work. But I cannot bring my work source code/environment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.