Using header files in C [closed]

帅比萌擦擦* 提交于 2019-12-08 05:38:28

问题


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'|


回答1:


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


来源:https://stackoverflow.com/questions/33820287/using-header-files-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!