C Primer Plus中文第六版,第12章内存类别/链接和内存管理中的掷骰子程序,如何将分开的几个程序翻译单元编译成功的。
C Primer Plus中文第六版,第12章内存类别/链接和内存管理中的掷骰子程序,如何将分开的几个翻译单元编译成功的。我是这么做的,在同一个文件夹中放置这几个程序,是然后编译程序12.1,但是编译显示12.1.cpp:(.text+0xc1): undefined reference to `roll_n_dice(int, int)'/12.1.cpp:(.text+0x12f): undefined reference to `roll_count'/[Error] ld returned 1 exit status。要怎么做才能编译成功,另麻烦推荐一下上机指导用书。12.1程序如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"diceroll.h"
int main(void)
{
int dice,roll;
int sides;
int status;
srand((unsigned int ) time(0));
printf("Enter the number of sides per die, 0 to stop.\n");
while((scanf("%d",&sides)==1&&sides>0))
{
printf("How many dice?\n");
if((status=scanf("%d",&dice))!=1)
{
if(status=EOF)
break;
else
{
printf("You should have entered an integer.");
printf("Let's begin again.\n");
while(getchar()!='\n')
continue;
printf("How many sides? Enter 0 to stop.\n" );
continue;
}
}
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 rollen() function was called %d times.\n",roll_count);
printf("GOOD FORTUNE TO YOU!\n");
return 0;
}
diceroll.h头文件(另存为头文件)
//diceroll.h
extern int roll_count;
int roll_n_dice(int dice,int sides);
12.2文件:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
double *ptd;
int max;
int number;
int i=0;
puts("What is the maximum number of type double entries?");
if(scanf("%d",&max)!=1)
{
puts("Number not correctly entered -- bye.");
exit(EXIT_FAILURE);
}
ptd=(double *) malloc(max *sizeof(double));
if(ptd==NULL)
{
puts("Memory allocation failed. Goodbye.");
exit(EXIT_FAILURE);
}
puts("Enter the values (q to quit):");
while(i<max)
{
scanf("lf",&ptd[i]);
++i;
}
printf("Here are your %d entries:\n",number=i);
for(i=0;i<number;i++)
{
printf("%7.2f",ptd[i]);
if(i%7==6)
putchar('\n');
}
if(i%7!=0)
putchar('\n');
puts("Done.");
free(ptd);
return 0;
}