在C中使用头文件 [英] Using header files in C
问题描述
main.c
>文件和 library.c
(其中存储了所有函数)和 library.h
(其中所有原型 在 main.c中
我将 #include库.h
但是当我尝试编译时,函数不能被识别。
我做错了什么?
我使用GCC构建文件。
test.c:
$ b
#includelibrary .h
int main()
{
int num = 5;
sum(num);
}
library.c
#includelibrary.h
int sum(int num)
{
返回num + 5;
}
library.h
#ifndef LIBRARY_H
#define LIBRARY_H
#include< stdio.h>
int sum(int num);
#endif
出错:
C:\ Users \Gabriel\Desktop\test.o:test.c ||未定义对`sum'的引用|
包含头文件是不够的。头文件中的原型只是告诉编译器应该有一个函数。
您必须将该函数实际添加到程序中。这是在链接时完成的。最简单的方法是
$ g $ p $ g $ gcc -o myprog test.c library.c
还有更复杂的选项。如果您想要将多个文件实际添加到库中,则可以独立编译它们并构建存档。
gcc -o library.o library.c
gcc -o someother.o someother.c
ar a libmy.a library.o someother.o
gcc -o myprog test.c -l my
I'm having a couple of issues including custom libraries in my program
I have my main.c
file and a library.c
(where all the functions are stored) and library.h
(where all the prototypes are stored).
In main.c
I'm placing #include "library.h"
but the functions don't get recognized when I try to compile.
Am I doing something wrong?
I'm using GCC to build the file.
test.c:
#include "library.h"
int main()
{
int num = 5;
sum(num);
}
library.c
#include "library.h"
int sum(int num)
{
return num + 5;
}
library.h
#ifndef LIBRARY_H
#define LIBRARY_H
#include <stdio.h>
int sum(int num);
#endif
Getting error:
C:\Users\Gabriel\Desktop\test.o:test.c|| undefined reference to `sum'|
Including the header file is not sufficient. The prototype in the header file just tells the compiler that there should be a function.
You have to actually add the function to the program. That is done when linking. the simplest way would be
gcc -o myprog test.c library.c
There are more sophisticated option. If you want to add several files actually to a library you can compile them independently and build the archive. Here are some commmands that show the basic idea.
gcc -o library.o library.c
gcc -o someother.o someother.c
ar a libmy.a library.o someother.o
gcc -o myprog test.c -l my
这篇关于在C中使用头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!