函数头和不同文件中的实现C.

Nam*_*tha 1 c header function definition

如何为函数提供头文件以及在不同文件中实现该函数?另外,你如何在另一个文件中使用main并调用此函数?优点是,这个功能将成为一个可以重复使用的独立组件,对吗?

abe*_*eln 5

这可以通过一个例子来说明.

假设我们想要一个函数来查找整数的立方体.

你会有定义(实现),比方说,cube.c

int cube( int x ) {
  return x * x * x;
}
Run Code Online (Sandbox Code Playgroud)

然后我们将函数声明放在另一个文件中.按照惯例,这是在头文件中完成的,cube.h在这种情况下.

int cube( int x );
Run Code Online (Sandbox Code Playgroud)

我们现在可以从其他地方调用该函数,driver.c例如,通过使用该#include指令(它是C预处理器的一部分).

#include "cube.h"

int main() {
  int c = cube( 10 );
  ...
}
Run Code Online (Sandbox Code Playgroud)

最后,您需要将每个源文件编译为目标文件,然后链接这些文件以获取可执行文件.

例如,使用gcc

$ gcc -c cube.c                 #this produces a file named 'cube.o'
$ gcc -c driver.c               #idem for 'driver.o'
$ gcc -o driver driver.c cube.c #produces your executable, 'driver'
Run Code Online (Sandbox Code Playgroud)