创建多个文件并在 C 中链接它们

Creating multiple files and linking them in C

我在 Linux cc 编译器中使用 C。我想要做的是创建一个包含主要功能的 main.c 文件。我还想创建一个 Special.c 文件,它没有主要功能,而是只有我想在需要时在 main.c 中调用的特殊功能。

我有更多 Java 的练习,例如在 Java 中,我将创建两个 类 并为此目的使用继承。

但由于我是 C 语言的新手,所以我不确定该怎么做。我知道可能有一种方法可以将 .h 文件与库一起使用,但我不确定如何在这里进行。

非常感谢任何帮助。

我将通过示例向您展示:

main.c 是具有您的主要功能的文件。

helper.h 包含您要在主函数中使用的函数的所有声明。 helper.c 有定义。

现在,从技术上讲,您可以在 helper.h 中定义函数,但这不是好的做法。

然后您需要:

#include "helper.h"  

在您的 main.c 程序之上。 最后,您需要将所有 .c 文件编译在一起。

喜欢:gcc main.c helper.c -o 输出

//main.c:
#include <stdio.h>
#include <helper.h>
int main()
{
int squareMe=5;
squareMe = helperFn(squareMe);
printf("%d", squareMe);

}

现在这在你的 helper.h:

int helperFn(int input); //only function declaration

终于在 helper.c:

#include "helper.h"

int helperFn(int i)
{
 return i*i;
}

假设 special.c 看起来像这样:

#include <stdio.h>

void special_func()
{
    printf("calling special_func\n");
}

你可以自己编译这个文件:

gcc -c special.c

这会生成 special.o。然后假设你有这个 main.c:

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

int main()
{
    printf("in main\n");
    special_func();
    return 0;
}

您的 main 函数调用 special_func,但它未在此文件中定义,因此需要知道如何调用它。这就是 special.h 内容的来源:

#ifndef SPECIAL_H
#define SPECIAL_H

void special_func();

#endif

这是一个函数原型。它声明了函数(即告诉您参数的数量和类型,以及 return 类型)而没有实际定义它。这允许它从其他编译单元调用。

所以现在你可以自己编译main.c:

gcc -c main.c

这将创建 main.o。现在你们可以 link 然后一起:

gcc -o program main.o special.o