标准库 include 应该写在哪里? .c 或 .h 文件?
Where should standard library include be writen ? .c or .h file?
我有以下简单的代码:
mainc.c:
#include <stdlib.h>
#include "hello.h"
int main (int argc, char *argv[])
{
hello ();
return EXIT_SUCCESS;
}
hello.c:
#include "hello.h"
void hello (void)
{
printf ("Hello world!");
}
hello.h:
#ifndef _HELLO_H_
#define _HELLO_H_
#endif
我需要在 hello 中包含 stdio.h 才能访问 printf() 函数。
我应该把它包括在哪里?在 hello.c 或 hello.h 中?是否有最佳实践,因为这两种解决方案似乎都是正确的?
Header 应用程序中的文件应仅包含系统 headers,这些文件需要在 header.
中声明更多接口
例如——如果您的 header 包含以 FILE *
作为参数的函数,它应该 #include <stdio.h>
。如果它声明一个包含 uint32_t
的结构,它应该 #include <stdint.h>
。等等。
系统 header 仅在实现中使用的应该留给 .c
文件。例如,您的 header 不应 #include <stdio.h>
仅仅因为实现调用 printf()
。
我有以下简单的代码:
mainc.c:
#include <stdlib.h>
#include "hello.h"
int main (int argc, char *argv[])
{
hello ();
return EXIT_SUCCESS;
}
hello.c:
#include "hello.h"
void hello (void)
{
printf ("Hello world!");
}
hello.h:
#ifndef _HELLO_H_
#define _HELLO_H_
#endif
我需要在 hello 中包含 stdio.h 才能访问 printf() 函数。
我应该把它包括在哪里?在 hello.c 或 hello.h 中?是否有最佳实践,因为这两种解决方案似乎都是正确的?
Header 应用程序中的文件应仅包含系统 headers,这些文件需要在 header.
中声明更多接口例如——如果您的 header 包含以 FILE *
作为参数的函数,它应该 #include <stdio.h>
。如果它声明一个包含 uint32_t
的结构,它应该 #include <stdint.h>
。等等。
系统 header 仅在实现中使用的应该留给 .c
文件。例如,您的 header 不应 #include <stdio.h>
仅仅因为实现调用 printf()
。