头文件与链接
Coddy 面向 PHP 开发者的 C 语言 课程的第 18 课,共 48 课。
PHP 的 require_once 会在运行时加载另一个文件,在每次脚本运行中最多加载一次,并且它声明的每个函数都会成为全局函数;PHP 没有文件私有函数。C 的 #include 是在编译前进行文本包含。将声明和共享类型放在带保护的头文件中,头文件的包含保护可以实现 _once 的功能;将定义放在源文件中,并且每个源文件只编译一次。文件作用域的 static 辅助函数仅在其所属的转换单元中可见。
PHP
<?php
function total(int $price, int $count): int
{
return $price * $count;
}
echo total(3, 4), PHP_EOL;C17
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
static int total(int price,int count){return price*count;}
int main(void) {
printf("%d\n",total(3,4));
return 0;
}
移植规则
通过带保护的头文件共享函数声明,并链接源文件中的定义。
挑战
简单将 subtotal(price,count) 实现为在 lesson.h 中声明的公共函数。如果有帮助,可以在 lesson.c 中使用私有的 static multiply 辅助函数。返回 price 乘以 count 的结果;评分器检查的是行为,而不是辅助函数的风格。
编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的锁定文件 main.c 兼容,该文件会直接调用它。不要添加另一个 main。除非任务明确检查数值范围,否则所有数值任务测试数据都足够小,不会溢出。只打印指定的输出;如果提供了驱动程序,它会负责解析输入和输出。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int a=0,b=0;if(scanf("%d%d",&a,&b)!=2)return 1;printf("%d\n",subtotal(a,b));return 0;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 PHP 开发者的 C 语言中的所有课
自己练习: C 在线编译器