歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> gcc(g++)多文件編譯的問題

gcc(g++)多文件編譯的問題

日期:2017/3/3 14:05:17   编辑:Linux技術

1.簡單程序(單模塊程序)的編譯

文件file1.c
[code]#include <stdio.h> 
int main()
{
        printf("hello\n");
        return 0;
}

文件file1.cpp
[code]#include <iostream>
using namespace std;

int main()
{
        cout<<"hello"<<endl;
        return 0;
}

編譯運行
[code]$ gcc file1.c -o file1
$ g++ file1.cpp -o file1_cpp
$ ./file1 
hello
$ ./file1_cpp
hello

對於只有一個文件的c/c++用GCC/G++來編譯很容易
對於多個文件即多個模塊的程序來說,其實也並不是很難.

2.多模塊程序的編譯

下面舉個例子:
文件first.h
[code]int first();

文件first.c
[code]#include "include.h"
#include "first.h"
first()
{
    printf("this is just a test!");
    return 0;
}

文件second.h
[code]int mymax(int,int);

文件second.c
[code]mymax(x,y)
{
    if(x>y)
        return x;
    else 
        return y;
}

文件main.c
[code]#include "first.h"
#include "second.h"
#include 
int main()
{
    int a,b;
    a=10;
    b=20;    
    first();
    printf("%d\n",mymax(a,b));
    return 0;
}

下面是在終端中輸入的內容
[code]$ gcc -c first.c
$ gcc -c second.c
$ gcc -c main.c
$ gcc first.o second.o main.o -o main
$ ./main
this is just a test!20

當然啦也可以這麼輸入
[code]$ gcc first.c second.c main.c -o main

不過以上的方法不是很好,因為對於文件數不是很多的程序,手動輸入以上幾個命令還不是很累,但如果是個文件數很多的程序呢,如果這樣輸入,那肯定會很累.
對於模塊數很多程序,我們可以寫一個makefile文件.然後使用make命令就可以了.

原文地址

http://blog.chinaunix.net/uid-20682749-id-2238158.html
Copyright © Linux教程網 All Rights Reserved