ubuntu10.10下配置C语言开发环境

来源:互联网 发布:vscode调整字体大小 编辑:程序博客网 时间:2024/05/22 14:36
1.安装GCC并检查版本
    sudo apt-get install build-essential
    注:安装了这个包会自动安装上g++,libc6-dev,linux-libc-dev,libstdc++6-4.1-dev等一些必须的软件和头文件的库。

    gcc --version
    注:ubuntu10.10下的GCC版本为GCC4.4.5

2.C语言程序testc.c测试
代码:
#include<stdio.h>
int main()
{
   printf("Hello Ubuntu!\n");
   return 0;
}

命令:
    $ gcc testc.c -o test
    注:将test.c预处理、汇编、编译并链接形成可执行文件test。-o选项用来指定输出文件的文件名。

命令:
    $ ./test
    注:路径 ./ 指代当前目录,因此 ./test 载入并执行当前目录下的可执行文件 ‘test’。


3.捕捉错误
编译器警告是非常重要,例如下面的例子包含一个微妙的错误:为一个整数值错误地指定了一浮点数控制符‘%f’。

代码:
#include <stdio.h>
int main (void)
{
    printf ("Two plus two is %f\n", 4);
    return 0;
}

该错误并不明显,但是它可被编译器捕捉到,只要启用了警告选项 -Wall。
编译上面的程序‘bad.c’,将得到如下的消息:
$ gcc -Wall -o bad bad.c
bad.c: In function ‘main’:
bad.c:6: warning: format ‘%f’ expects type ‘double’, but argument 2 has type ‘int’

这表明文件 ‘bad.c’第 6 行中的格式字符串用法不正确。
如果不启用 -Wall,程序表面看起来编译正常,但是会产生不正确的结果.

4.编译多个源文件
一个源程序可以分成几个文件。这样便于编辑与理解,尤其是程序非常大的时候。这也使各部分独立编译成为可能。
下面的例子中我们将程序 Hello World 分割成 3 个文件:‘hello.c’,‘hello_fn.c’和头文件‘hello.h’。这是主程序‘hello.c’:

hello.c代码:
#include "hello.h"
int main(void)
{
    hello ("world");
    return 0;
}

hello.h代码:
void hello (const char * name);

hello_fn.c代码:
#include <stdio.h>
#include "hello.h"

void hello (const char * name)
{
    printf ("Hello, %s!\n", name);
}
注:#include "FILE.h" 表示在搜索系统头文件目录之前将先在当前目录中搜索文件‘FILE.h’,
   #include <FILE.h> 表示只搜索系统头文件而不查看当前目录。

命令:   
    $ gcc -Wall hello.c hello_fn.c -o newhello
    注:用选项 -o 为可执行文件指定了一个不同的名字 newhello。注意到头文件‘hello.h’并未在命令行中指定。源文件中的的 #include "hello.h" 指示符使得编译器自动将其包含到合适的位置。


命令:   
    $ ./newhello
     注:显示Hello, world!

5.简单的make
    Make 从 makefile(默认是当前目录下的名为‘Makefile’的文件)中读取项目的描述。makefile指定了一系列目标(比如可执行文件)和依赖(比如对象文件和源文件)的编译规则,其格式如下:
    目标: 依赖
          命令

为上一节的项目写一个简单的 make file 文件
CC=gcc
CFLAGS=-Wall
hello: hello.o hello_fn.o
clean:
    rm -f hello hello.o hello_fn.o

注:CC表示C语言编译器,CFLASS表示编译器选项,目标clean没有依赖文件,它只是简单地移除所有编译生成的文件。rm命令的选项 ‘-f’(force) 抑制文件不存在时产生的错误消息。

运行命令make,得到如下结果
     sinkingboat@sinkingboat-Aspire-4710:~$ make
     gcc   hello.o hello_fn.o   -o hello
原创粉丝点击