C Primer Plus--- Chapter 9---Functions ---2.编译多个文件
程序员文章站
2024-02-29 17:27:22
...
C Primer Plus--- Chapter 9---Functions ---2.编译多个文件
可以将程序放在几个分开的文件中,将函数声明和常量的定义存放在一个头文件中,见下面例子:
第一个文件,存放主函数:
Listing 9.9 The usehotel.c Control Module
/* usehotel.c -- room rate program */
/* compile with Listing 9.10 */
#include <stdio.h>
#include "hotel.h" /* defines constants, declares functions */
int main(void)
{
int nights;
double hotel_rate;
int code;
while ((code = menu()) != QUIT)
{
switch(code)
{
case 1 : hotel_rate = HOTEL1;
break;
case 2 : hotel_rate = HOTEL2;
break;
case 3 : hotel_rate = HOTEL3;
break;
case 4 : hotel_rate = HOTEL4;
break;
default: hotel_rate = 0.0;
printf("Oops!\n");
break;
}
nights = getnights();
showprice(hotel_rate, nights);
}
printf("Thank you and goodbye.\n");
return 0;
}
第二个文件,存放函数定义
Listing 9.10 The hotel.c Function Support Module
/* hotel.c -- hotel management functions */
#include <stdio.h>
#include "hotel.h"
int menu(void)
{
int code, status;
printf("\n%s%s\n", STARS, STARS);
printf("Enter the number of the desired hotel:\n");
printf("1) Fairfield Arms 2) Hotel Olympic\n");
printf("3) Chertworthy Plaza 4) The Stockton\n");
printf("5) quit\n");
printf("%s%s\n", STARS, STARS);
while ((status = scanf("%d", &code)) != 1 ||
(code < 1 || code > 5))
{
if (status != 1)
scanf("%*s"); // dispose of non-integer input
printf("Enter an integer from 1 to 5, please.\n");
}
return code;
}
int getnights(void)
{
int nights;
printf("How many nights are needed? ");
while (scanf("%d", &nights) != 1)
{
scanf("%*s"); // dispose of non-integer input
printf("Please enter an integer, such as 2.\n");
}
return nights;
}
void showprice(double rate, int nights)
{
int n;
double total = 0.0;
double factor = 1.0;
for (n = 1; n <= nights; n++, factor *= DISCOUNT)
total += rate * factor;
printf("The total cost will be $%0.2f.\n", total);
}
第三个文件, 自定义头文件,存放函数声明和常量定义
Listing 9.11 The hotel.h Header File
/* hotel.h -- constants and declarations for hotel.c */
#define QUIT 5
#define HOTEL1 180.00
#define HOTEL2 225.00
#define HOTEL3 255.00
#define HOTEL4 355.00
#define DISCOUNT 0.95
#define STARS "**********************************"
// shows list of choices
int menu(void);
// returns number of nights desired
int getnights(void);
// calculates price from rate, nights
// and displays result
void showprice(double rate, int nights);
这几个程序存放在同一个文件夹,编译时要同时编译第一个和第二个程序:
gcc -g usehotel.c hotel.c -o hotel.o