天天看點

Linux編譯C檔案

熟悉了Windows平台下編譯一個C++工程後,你是否會提出這樣一個問題:在Linux平台下又如何編譯一個C++工程呢?

希望本文能給正在學習或想學習Linux C++開發的你起到抛磚引玉的作用。

首先,你必須有一個Linux開發環境,這樣才能進行C++開發。筆者用的是安裝在虛拟機中的Ubuntu 9.04,Ubuntu作業系統是沒帶C++編譯器g++。在連網的情況下,在終端中使用root超級使用者權限輸入以下指令:

sudo apt-get install g++

并回車即可安裝C++編譯器g++。

安裝完畢,即可開始建立我們的一個C++工程了。下面以一個hello工程為例,簡單地介紹如何編譯一個 C++工程。

登入Linux系統,打開終端,在目前目錄下使用mkdir指令建立一個hello的目錄;然後使用cd hello進入hello目錄中,并使用vi工具建立hello.h、hello.cpp、main.cpp、makefile四個檔案。四個檔案的内容分别如下:

1. hello.h檔案

#ifndef HELLO_H_

#define HELLO_H_

class Hello {

public:

void print();

};

#endif

2. hello.cpp檔案

#include "hello.h"

#include <iostream>

using namespace std;

void Hello::print() {

        cout<<"Hello, welcome to Redhat Linux os!"<<endl;

}

3. main.cpp檔案

#include "hello.h"

#include <iostream>

using namespace std;

int main() {

     Hello h;

     h.print();

     return 0;

}

注意:這三個檔案要以空白行結束,否則編譯時會有警告資訊。

4. makefile檔案

# this is a makefile of the c++ project hello

# the standard c++ compiler in the Redhat linux is g++

# written by young on June 27th, 2009

      TARGET = .

          CC = g++

      CFLAGS = -g

      CFLAGC = -c

      MAINC = main.cpp

      HELLO = hello.cpp

        OBJ = hello.o

      INCLUDE = -I$(TARGET)

         EXEC = $(TARGET)/main

all: $(EXEC)

$(EXEC): $(OBJ) $(MAINC)

$(CC) $(CFLAGS) $(OBJ) $(MAINC) $(INCLUDE) -o [email protected]

rm -f $(OBJ)

@echo "<<<<<< [email protected] is created successfully! >>>>>>"

$(OBJ): $(HELLO)

$(CC) $(CFLAGC) $(HELLO) -o [email protected]

clean:

rm -f $(EXEC)

注意: makefile檔案中的指令行(紅色字型)一定要以Tab建開頭,否則編譯通不過。

寫好makefile檔案後,即可編譯工程。在終端中輸入make指令,回車後将顯示如下資訊:

g++ -c hello.cpp -o hello.o

g++ -g hello.o main.cpp -I. -o main

rm -f hello.o

<<<<<< main is created successfully! >>>>>>

這些資訊說明工程已被正确編譯,目前目錄下将生成一個main的可執行檔案。

同樣,你也可以不使用makefile檔案,而直接在終端上輸入以下兩行指令:

g++ -c hello.cpp -o hello.o

g++ -g hello.o main.cpp -I. -o main

也可以編譯這個工程。

使用ls -l指令檢視目前目錄下的所有檔案,确實有一個main檔案。

在終端中輸入./main,即可運作程式。

繼續閱讀