c - 如何使用 .h 和几个 .c 文件将程序拆分为多个文件?
问题描述
我试图弄清楚将程序拆分为多个文件以拥有 1 个.h文件和 2 个.c文件。我有一个完整的程序,但对于这个例子,我希望打印输出的功能在一个单独的 .c 文件中。我知道如何制作基本算术的函数,例如:
int Sum(int a, int b)
{
return a+b;
}
但是我将如何使用 for 循环和下面的代码创建一个函数?
for (i = 0; i < count; i++)
{
printf("\n%s", ptr[i]->name);
printf("%s", ptr[i]->street);
printf("%s", ptr[i]->citystate);
printf("%s", ptr[i]->zip);
free(ptr[i]);
}
我知道它的工作方式是这样的,只是不知道如何将 for 循环变成一个函数。
函数.h:
#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED
/* ^^ these are the include guards */
/* Prototypes for the functions */
/* Sums two ints */
int Sum(int a, int b);
#endif
函数.c:
/* In general it's good to include also the header of the current .c,
to avoid repeating the prototypes */
#include "Functions.h"
int Sum(int a, int b)
{
return a+b;
}
主程序
#include "stdio.h"
/* To use the functions defined in Functions.c I need to #include Functions.h */
#include "Functions.h"
int main(void)
{
int a, b;
printf("Insert two numbers: ");
if(scanf("%d %d", &a, &b)!=2)
{
fputs("Invalid input", stderr);
return 1;
}
printf("%d + %d = %d", a, b, Sum(a, b));
return 0;
}
解决方案
推荐阅读
- hadoop - 使用 hive 在 gcp 中跨项目访问存储桶
- c++ - 获取已保存的事件 Visual Studio DTE
- php - php 中的 Soap Api 实现,由提供的 Wsdl 和 enpoint
- android - 布局之间的空白
- reactjs - 如何在 React Native 中创建全局布局组件?
- java - CompletableFuture 简化自定义示例
- url - 如何使用完全限定的服务器名称地址访问 Rabbitmq 管理 UI?
- python - Python 日期格式
- quaternions - 妙手镯;如何从四元数到前臂方向单位向量?
- nginx - Unirest 连接超时