C语言报No such file or directory异常和undefined reference error: ld returned 1 exit status异常

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sjdjdjdjahd/article/details/89508983

这两个错误都是在引用自己的定义的头文件时报的。

一、fatal error: function.h: No such file or directory异常

1、创建function.h文件,里面有个add()方法的方法名
#include <stdio.h>

int add(int a,int b);
2、创建function.c文件,引用function.h。里面是方法的实现
#include "E:/Dev/c/test/function.h"

int add(int a,int b){
    return a+b;
}
3、在main()方法中引用
#include <stdio.h>
#include "E:/Dev/c/test/function.h"

int main(){
    int s = add(1,2);
    printf("add(1,2)=%d",s);
    return 0;
}

引用注意:#include "完整路径/function.h"

这里引用自己定义的文件的时候,要加上全路径才行,否则会报fatal error: function.h: No such file or directory异常。
在这里插入图片描述

二、undefined reference error: ld returned 1 exit status异常

这个异常时编译的时候,只编译了main()方法所在的文件,没有编译function.c所造成的。
在这里插入图片描述
因为function.c没有编译,所以找不到‘add’方法。
这里只需要编译的时候把function.c一起编译就行。

gcc hello.c function.c -o hollo.exe

hello.c就是调用function.h的文件。
运行截图:
在这里插入图片描述
部分参考:“undefined reference to” 问题解决方法

猜你喜欢

转载自blog.csdn.net/sjdjdjdjahd/article/details/89508983