首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

怎的包含另一个文件

2013-01-01 
怎样包含另一个文件?两个文件,一个是函数,另一个是主文件,主文件调用函数文件用#included.h。我想问的是,

怎样包含另一个文件?
两个文件,一个是函数,另一个是主文件,主文件调用函数文件用#include"d.h"。
我想问的是,怎样保存才能函数文件能被调用?
我用的方法是在一个工程里建两个文件,行不通。
然后建两个文件,一个d.h,一个d1.c,也行不通。。
主文件:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include "d.h"

int main(void)
{
int dice,roll;
int sides;

srand((unsigned int)time(0));
printf("Enter the number of sides per die,0to stop.\n");
while(scanf("%d",&sides)==1&&sides>0)
{
printf("How many dice?\n");
scanf("%d",&dice);
roll=roll_n_dice(dice,sides);
printf("You have rolled a %d using %d %d-sided dice.\n",
roll,dice,sides);
printf("How many sides?Enter 0 to stop.\n");
}
printf("The rollem()function was called %d times.\n",roll_count);
printf("GOOD FORTUNE TO YOU!\n");
return 0;
}


另一个文件
#include "d.h"
#include<stdio.h>
#include<stdlib.h>

int roll_count=0;
static int rollem(int sides)
{
int roll;
roll=rand()%sides+1;
++roll_count;
return roll;
}

int roll_n_sides(int dice,int sides)
{
int d;
int total=0;
if(sides<2)
{
printf("Need at least 2 sides.\n");
return -2;
}
if(dice<1)
{
printf("Need at least 1 die.\n");
return -1;
}
for(d=0;d<dice;d++)
total+=rollem(sides);

return total;
}

[解决办法]
函数的定义或函数原型放在.h文件中
函数的实现放在.c或.cpp文件中

d1.c
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include "d.h"

int main(void)
{
    int dice,roll;
    int sides;

    srand((unsigned int)time(0));
    printf("Enter the number of sides per die,0to stop.\n");
    while(scanf("%d",&sides)==1&&sides>0)
    {
        printf("How many dice?\n");
        scanf("%d",&dice);
        roll=roll_n_dice(dice,sides);
        printf("You have rolled a %d using %d %d-sided dice.\n",
            roll,dice,sides);
        printf("How many sides?Enter 0 to stop.\n");
    }
    printf("The rollem()function was called %d times.\n",roll_count);
    printf("GOOD FORTUNE TO YOU!\n");
    return 0;
}


d.c

#include<stdio.h>
#include<stdlib.h>
public int roll_count=0;
static int rollem(int sides)
{
    int roll;
    roll=rand()%sides+1;
    ++roll_count;
    return roll;
}

int roll_n_sides(int dice,int sides)
{


    int d;
    int total=0;
    if(sides<2)
    {
        printf("Need at least 2 sides.\n");
    return -2;
    }
    if(dice<1)
    {
        printf("Need at least 1 die.\n");
        return -1;
    }
    for(d=0;d<dice;d++)
        total+=rollem(sides);

    return total;
}



d.h

extern int roll_count=0;
static int rollem(int sides);
int roll_n_sides(int dice,int sides);

将d1.c和d.c添加到同一个项目的源文件中。

热点排行