首页 > 解决方案 > 如何使用 .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;
 }

标签: c

解决方案



推荐阅读