一、程序
main.c
#include <stdio.h>
#include "sub.h"
int main()
{
int a, b, c;
printf("请依次输入被减数和减数:\n");
scanf("%d%d", &a, &b);
printf("a=%d, b=%d\n", a, b);
c = sub(a, b);
printf("result: %d - %d = %d\n", a, b, c);
return 0;
}
sub.c
#include <stdio.h>
int sub(int a, int b)
{
return (a - b);
}
sub.h
#ifndef SUB_H
#define SUB_H
int sub(int a, int b);
#endif
Makefile
sub: main.o sub.o
gcc -o sub main.o sub.o
%.o: %.c
gcc -c $<
clean:
rm -rf *.o sub
二、运行
将上述四个文件放到同一个文件夹下,比如我放到了桌面的test文件夹中,路径:/home/clay/桌面/test
快捷键ctrl+shift+T
打开终端,进入到该路径,命令如下:
cd /home/clay/桌面/test
接着输入make
运行程序,效果如下图:
接着输入./sub
运行可执行文件,效果如下图:
按照提示,输入被减数和减数,这里以8 3
为例,效果如下图:
三、对比上一次的那一道题
编写程序,main.c调用fun1.c输出“This is fun1!”,调用fun2.c输出“This is fun2!”,注意两个字符串输出均有换行。
(1)、编写三个源文件
(2)、编写生成work可执行文件的Makefile
解题过程如下:
(1)
main.c
#include <stdio.h>
#include "fun1.h"
#include "fun2.h"
int main()
{
fun1();
fun2();
return 0;
}
fun1.c
#include <stdio.h>
void fun1(void)
{
printf(“This is fun1! \n”);
}
fun2.c
#include <stdio.h>
void fun2(void)
{
printf(“This is fun2! \n”);
}
fun1.h
#ifndef _FUN1_H
#define _FUN1_H
void fun1();
#endif
fun2.h
#ifndef _FUN2_H
#define _FUN2_H
void fun2();
#endif
(2)
Makefile
work: main.o fun1.o fun2.o
gcc -o work main.o fun1.o fun2.o
%.o: %.c
gcc -c $<
clean:
rm -rf *.o work