gpt4 book ai didi

c - 如果不包含 .c,头文件中的函数也无法工作

转载 作者:行者123 更新时间:2023-11-30 18:54:59 25 4
gpt4 key购买 nike

我尝试用 C 语言编写程序,但如果不包含 .c 文件,我就无法使用 .h 中的函数。如果我在包含 .h 之后包含 .c ,它就可以工作。我在 .h 中定义的每个函数上都收到“ undefined reference ...”错误。

main.c:

#include "mp.h"
//#include "mp.c"
int main()
{
int n;
printf("Unesite broj clanova niza: ");
scanf("%d",&n);
int *a=(int *)malloc(n*sizeof(int));
if (a==NULL) exit(0);
unos(a,n);
sortiranje(a,n,rastuci);
stampanje(a,n);
sortiranje(a,n,opadajuci);
stampanje(a,n);
return 0;
}

mp.h:

#ifndef MP_H_INCLUDED
#define MP_H_INCLUDED


#include <stdio.h>
#include <stdlib.h>
enum tip_sort {opadajuci,rastuci};
void unos(int *, int);
void sortiranje(int *, int, enum tip_sort);
void stampanje(int *, int);

#endif // MP_H_INCLUDED

mp.c:

#include "mp.h"


void unos(int *a, int n){
...
}
void sortiranje(int *a, int n, enum tip_sort t){
...
}
void stampanje(int *a, int n){
...
}

最佳答案

您看到的是链接器错误。我猜,您正在尝试单独编译 main.c

你的编译语句应该看起来像

gcc main.c mp.c -o output

是的,不要 #include .c(源)文件。源文件旨在被编译并链接在一起以形成二进制文件。

注意:另外,请do not cast malloc() 的返回值。

关于c - 如果不包含 .c,头文件中的函数也无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29152852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com