Linux程序设计学习系列(第一章)

ubuntu下配置c运行环境及示例

环境配置

ubuntu默认不包含编辑器vim和编译器gcc。因此首先要将所需要的运行环境安装配置好。
1.apt-get update
2.安装vim:sudo apt-get install vim
3.安装gcc:sudo apt-get install g++

编写hello.c源代码

  1. 新建文件名为hello.c的源文件:输入vim hello.c
  2. 键入i 进入insert模式(即编辑输入模式),写入如下经典代码:
//the first program hello.c
#include<stdio.h>
int main(void)
{
printf("Hello, world!\n");
return 0;
}
  1. 输入完成后,Esc 回到normal模式,键入:wq 保存退出vim。
  2. 编译hello.c: g++ hello.c -o hello (将c语言源代码转换为可执行文件hello)
  3. 运行程序hello:./hello就可以看到运行结果了

静态库实验

创建小型的函数库,包含两个函数,之后在一个程序中调用其中一个函数。

  1. fred.c
#include<stdio.h>
void fred(int arg){
printf("fred:we passed %d\n",arg);
}
  1. bill.c
#include<stdio.h>
void bill(char *arg)
{
printf("bill:we passed %s\n",arg);
}

分别编译这些函数, -c选项是阻止编译器创建一个完整程序,因为现在还没有main函数,所以试图创建一个完整的程序不会成功。

gcc -c bill.c fred.c
ls *.o

这时就可以看到bill.o和fred.o

  1. lib.h
    这个文件相当于头文件,其中会声明库文件中的函数。
/* This is the lib.h.It declares the functions fred and bill for users*/
void bill(char *);
void fred(int);
  1. program.c
    此程序包含库的头文件并且调用库中的一个函数。
#include <stdlib.h>
#include "lib.h"
int main(){
bill("Hello world");
exit(0);
}
  1. 编译和测试:
gcc -c program.c
gcc -o program program.o bill.o
./program

显示:
bill:we passed Hello World

6.创建并使用库文件。用ar程序创建一个归档文件并将目标文件添加进去。

root@xhj-2:/usr/linuxProgramming# ar crv libfoo.a bill.o fred.o
a - bill.o
a - fred.o

7.为函数库生成内容表。

ranlib libfoo.a

现在,函数可库可以使用了,可以在编译器使用的文件列表中添加该库文件以创建程序,如下所示。

gcc -o program program.o libfoo.a
./program

显示 bill:we passed Hello World

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值