【问题标题】:How to call a function from another .c file如何从另一个 .c 文件调用函数
【发布时间】:2020-04-26 04:09:30
【问题描述】:

我写了一个程序,在 main 函数中调用另一个 .c 文件中的函数,但输出错误 对“function_name”的未定义引用。 collect2:错误:ld 返回 1 个退出状态。 我在Linux命令行上编译程序:gcc -o main.exe main.c ./main.exe

funcs.h

#ifndef FUNCS_H_INCLUDED
#define FUNCS_H_INCLUDED

int foo();

#endif

秒.c

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

int foo(){
  printf("Hello, world!");

return 0;
}

main.c

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

int foo();

int main(){
  foo();

  return 0;
}

如何修复错误

【问题讨论】:

    标签: c


    【解决方案1】:

    你需要编译所有的c文件,而不仅仅是main.c

    gcc -o main.exe main.c second.c
    

    【讨论】:

    • funcs.c -> second.c
    • @FiddlingBits 已修复,谢谢!
    【解决方案2】:

    未检测到特定函数的符号时会引发未定义的引用。

    在这种情况下,可以修复编译包含该函数的 .c 文件:

    gcc -o main.exe main.c second.c
    

    通过这种方式,您将在 funcs.c 文件中获得您调用的函数的符号。

    【讨论】:

    • funcs.c -> second.c
    猜你喜欢
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2013-12-17
    • 1970-01-01
    • 2015-07-14
    相关资源
    最近更新 更多