第 16 章 C 预处理器和 C 库(条件编译)

时间:2023-03-08 23:52:04
第 16 章 C 预处理器和 C 库(条件编译)
 /*--------------------------------------
names_st.h -- names_st 结构的头文件
--------------------------------------*/
#ifndef NAMES_ST_H
#define NAMES_ST_H #include <string.h> #define SLEN 32 //结构声明
struct names_st
{
char first[SLEN];
char last[SLEN];
}; //类型定义
typedef struct names_st names; //函数原型
void get_names(names*);
void show_names(const names*);
char* s_gets(char *st, int n); #endif

names_st.h

 /*-----------------------------------------
names_st.c -- 定义 names_st.h 中的函数
-----------------------------------------*/ #include <stdio.h>
#include "names_st.h" //包含头文件 //函数定义
void get_names(names *pn)
{
printf("Please enter your first name: ");
s_gets(pn->first, SLEN); printf("Please enter your last name: ");
s_gets(pn->last, SLEN);
} void show_names(const names *pn)
{
printf("%s %s", pn->first, pn->last);
} char* s_gets(char *st, int n)
{
char *ret_val, *find; if (ret_val = fgets(st, n, stdin))
{
if (find = strchr(st, '\n'))
*find = '\0';
else
while (fgetc(stdin) != '\n') continue; //处理输入行中的剩余字符
} return ret_val;
}

names_st.c

 /*----------------------------------------
useheader.c -- 使用 names_st 结构
----------------------------------------*/ #include <stdio.h>
#include "names_st.h"
#include "names_st.h" //第2次包含头文件 int main()
{
names candidate; get_names(&candidate);
printf("Let's welcome ");
show_names(&candidate);
printf(" to this program!\n"); return ;
}

useheader.c

第 16 章 C 预处理器和 C 库(条件编译)