现在的位置: 首页 > 综合 > 正文

gcc(g++)多文件编译

2017年06月16日 ⁄ 综合 ⁄ 共 1107字 ⁄ 字号 评论关闭

1.简单程序(单模块程序)的编译
文件file1.c
#include <stdio.h>
int main(){
        printf("hello\n");
         return 0;
}

文件file1.cpp
#include <iostream>
using std::cout;
using std::endl;

int main()
{
        cout<<"hello"<<endl;
        return 0;
}
[xiaochen@freeware ~]$ gcc file1.c -o file1
[xiaochen@freeware ~]$ g++ file1.cpp -o file1_cpp
[xiaochen@freeware ~]$ ./file1 
hello
[xiaochen@freeware ~]$ ./file1_cpp
hello

对于只有一个文件的c/c++用GCC/G++来编译很容易

对于多个文件即多个模块的程序来说,其实也并不是很难.
2.多模块程序的编译
下面举个例子:
文件first.h
int first();
文件first.c
#include <stdio.h>
#include "first.h"
first()
{
        printf("this is just a test!");
        return 0;
}
文件second.h
int mymax(int,int);
文件second.c
mymax(x,y)
{
        if(x>y)
                return x;
        else 
        return y;
}
文件main.c
#include "first.h"
#include "second.h"
#include <stdio.h>
int main()
{
        int a,b;
        a=10;
        b=20;   
        first();
        printf("%d\n",mymax(a,b));
        return 0;
}

下面是在终端中输入的内容
[xiaochen@freeware ~]$ gcc -c first.c
[xiaochen@freeware ~]$ gcc -c second.c
[xiaochen@freeware ~]$ gcc -c main.c
[xiaochen@freeware ~]$ gcc first.o second.o main.o -o main
[xiaochen@freeware ~]$ ./main
this is just a test!20
当然啦也可以这么输入
[xiaochen@freeware ~]$ gcc first.c second.c main.c -o main

抱歉!评论已关闭.