代码之家  ›  专栏  ›  技术社区  ›  ecjb

如何用C语言中的makefile通过文件间函数调用构建具有多个文件的程序

  •  0
  • ecjb  · 技术社区  · 3 年前

    我正在努力构建一个包含多个文件的程序,其中使用C中的makefile进行文件间函数调用。假设我有一个调用函数的主文件 call_print_hello() 在头文件中声明 fdeclar_macros.h 并写入文件 script1.c .功能 call_print_hello() 本身调用另一个函数 print_hello() 也在中声明 fdeclar_macross。h 并写入 script2.c 。我还有一个 makefile 但当我运行它时,我会收到以下错误消息:

    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
    

    以下是文件的内容:

    生成文件 :

    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
        ./main
    
    clean:
        $(RM) -rf justify *.dSYM *.o
    

    main.c :

    #include "fdeclar_macros.h"
    
    int main(){
      call_print_hello();
      return 0;
    }
    

    fdeclar_macross。h :

    
    #define NUMBER 3
    
    void print_hello();
    void call_print_hello();
    

    script1.c :

    #include <stdio.h>
    #include "fdeclar_macros.h"
    
    void print_hello(){
      printf("hello %d\n", NUMBER);
    }
    

    script2.c :

    #include "fdeclar_macros.h"
    
    void call_print_hello(){
      print_hello();
    }
    
    1 回复  |  直到 3 年前
        1
  •  2
  •   ndim    3 年前

    的make目标 main 可执行文件不包含对的依赖项 script2.o 以及要建立的规则 主要的 不链接 script2.o 进入 主要的 可执行。

    因此,链接器尝试使用的内容构建一个可执行文件 script2.o 缺少,但由于该内容是必需的,因此链接失败。

    一个简单的解决方案是更改原始规则

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

    通过添加 script2.o :

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

    我将把寻找更一般的规则留给读者练习。

        2
  •  1
  •   niki    3 年前
    NAME = my_programm
    CC = gcc
    CFLAGS = -Wall -Werror -Wextra
    MY_SOURCES = main.c script1.c script2.c
    MY_OBJECTS = $(MY_SOURCES:.c=.o)
    
    $(NAME): $(MY_OBJECTS)
        @cc $(CFLAGS) $(MY_OBJECTS) -o $(NAME)
    
    clean:
        @rm -f $(MY_OBJECTS)
        @rm -f $(NAME)
    
    run:
        ./my_programm