-->

如何创建C头文件[关闭]如何创建C头文件[关闭](How can I create C header

2019-05-12 18:17发布

我希望能够创造的头文件功能,我可以在我的C程序的一个#包括集合。

Answer 1:

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$


Answer 2:

头文件可以包含任何有效的C代码,因为它们通过在编译之前预处理器注入编译单元。

如果一个头文件包含一个函数,由多个包含.c文件,每个文件.c文件将获得该功能的副本,并为它建立一个符号。 链接器会抱怨重复的符号。

这在技术上是可以创建static中纳入多个头文件中的函数.c文件。 虽然这通常是没有这样做,因为它从代码中发现的惯例打破.c文件和声明中发现.h文件。

看到在讨论C / C ++:在头文件中的静态函数,这是什么意思? 对于更多的解释。



文章来源: How can I create C header files [closed]