情報処理のWeb教科書―IPA情報処理試験対策のお供に!

gcc―分割コンパイルなどC言語の無料ソフト&コマンドで学ぶC言語入門テキスト

トップ プログラミング C言語 中級 gcc

分割コンパイルやユーザ定義のヘッダーファイルの活用などgccコマンドの知識が必要です。gccコマンドのオプションの知識およびgccコンパイラーの使い方について掘り下げていきます。

▲記事トップへ

目次

この記事の目次です。

1. gccコンパイラのインストール
2. gccコマンドのオプション一覧
3. C言語の入門プログラムのコンパイル
4. 分割コンパイル
5. ヘッダーファイルの作成方法
6. 共有ライブラリの作成方法
7. その他のオプション

もっと知識を広げるための参考
更新履歴

1. gccコンパイラのインストール

以降ではWindowsとLinux上にgccをインストールする方法を見ていきます。

MinGWは Minimalist GNU for Windows"の略で、ネイティブのWindowsアプリケーションを開発するために必要な最小限の環境を提供するツールセットがまとめられています。

Windows版のgccのMinGWのインストール

Windows版のgccコンパイラのMinGWのインストール方法について解説しています。

詳細

Linux版のgccのインストール

Linux版のgccのインストール方法についてみていきます。

Debian系

UbuntsなどDebian系はopt-getでインストールできます。

$ sudo apt-get install gcc

CentOSなどRed Hat系

CentOSやFedraなどRed Hat Enterprise Linux系はyumでインストールできます。

$ sudo yum install gcc

参考)Linux

Linuxとは、WindowsやMacと同じOSの1つです。読み方はリナックスです。Linuxとはどのようなものかの説明を簡単にまとめています。 またネタとして使える日本産の軽量ディストリビューションのlinuxbeanの情報、コマンドラインの「$」「#」「cd」「~」記号の意味などの入門者にとってよくわからない点をわかりやすくまとめています。

詳細

2. gccコマンドのオプション一覧

gccコマンドのオプションは--helpオプションで確認できます。以下はその出力になります。

> gcc --help
Usage: gcc [options] file...
Options:
  -pass-exit-codes         Exit with highest error code from a phase
  --help                   Display this information
  --target-help            Display target specific command line options
  --help={common|optimizers|params|target|warnings|[^]{joined|separate|undocumented}}[,...]
                           Display specific types of command line options
  (Use '-v --help' to display command line options of sub-processes)
  --version                Display compiler version information
  -dumpspecs               Display all of the built in spec strings
  -dumpversion             Display the version of the compiler
  -dumpmachine             Display the compiler's target processor
  -print-search-dirs       Display the directories in the compiler's search path
  -print-libgcc-file-name  Display the name of the compiler's companion library
  -print-file-name=<lib>   Display the full path to library <lib>
  -print-prog-name=<prog>  Display the full path to compiler component <prog>
  -print-multiarch         Display the target's normalized GNU triplet, used as
                           a component in the library path
  -print-multi-directory   Display the root directory for versions of libgcc
  -print-multi-lib         Display the mapping between command line options and
                           multiple library search directories
  -print-multi-os-directory Display the relative path to OS libraries
  -print-sysroot           Display the target libraries directory
  -print-sysroot-headers-suffix Display the sysroot suffix used to find headers
  -Wa,<options>            Pass comma-separated <options> on to the assembler
  -Wp,<options>            Pass comma-separated <options> on to the preprocessor
  -Wl,<options>            Pass comma-separated <options> on to the linker
  -Xassembler <arg>        Pass <arg> on to the assembler
  -Xpreprocessor <arg>     Pass <arg> on to the preprocessor
  -Xlinker <arg>           Pass <arg> on to the linker
  -save-temps              Do not delete intermediate files
  -save-temps=<arg>        Do not delete intermediate files
  -no-canonical-prefixes   Do not canonicalize paths when building relative
                           prefixes to other gcc components
  -pipe                    Use pipes rather than intermediate files
  -time                    Time the execution of each subprocess
  -specs=<file>            Override built-in specs with the contents of <file>
  -std=<standard>          Assume that the input sources are for <standard>
  --sysroot=<directory>    Use <directory> as the root directory for headers
                           and libraries
  -B <directory>           Add <directory> to the compiler's search paths
  -v                       Display the programs invoked by the compiler
  -###                     Like -v but options quoted and commands not executed
  -E                       Preprocess only; do not compile, assemble or link
  -S                       Compile only; do not assemble or link
  -c                       Compile and assemble, but do not link
  -o <file>                Place the output into <file>
  -pie                     Create a position independent executable
  -shared                  Create a shared library
  -x <language>            Specify the language of the following input files
                           Permissible languages include: c c++ assembler none
                           'none' means revert to the default behavior of
                           guessing the language based on the file's extension

Options starting with -g, -f, -m, -O, -W, or --param are automatically
 passed on to the various sub-processes invoked by gcc.  In order to pass
 other options on to these processes the -W<letter> options must be used.

For bug reporting instructions, please see:
<http://gcc.gnu.org/bugs.html>.

3. C言語の入門プログラムのコンパイル

C言語の簡単なプログラムが記述できるようにするため、初歩的な構文や制御構造について解説していきます。 なお、特に断らない限りWindows版のgccの例を記載しています。

C言語のプログラムの作成の流れ

C言語のプログラムは、ソースコードを記述したソースファイルを作成し、ソースファイルのコンパイル(リンク)を行って実行形式ファイルを作成します。 そして、実行形式ファイルを起動することでプログラムが実行出来ます。

たとえば、作成から実行までは次のような流れになります。

  1. 拡張子が「.c」のテキストファイルにC言語のプログラムを記述します。 プログラムが記述されたファイルをソースファイルといいます。
  2. 「gcc ソースファイルのパス」のコマンドを実行して、ソースファイルをコンパイルします。 ソースファイルと同じディレクトリに、実行ファイルが作成されます。
  3. プログラムを実行します。

ここで作成するプログラムについて解説

ここではコマンドラインに「Hello World!!」と表示するプログラムを作成します。

ソースファイルの作成

Windowsに標準で搭載されているnotepadエディタを使用してソースファイルを作成します。

コマンドプロンプトを起動して、ファイル名を指定して、notepadコマンドを実行します。

notepad hello.c

以下のコードを入力して、保存します。

#include <stdio.h>

int main(void) {
	printf("Hello World!!\n");
	return 0;
}

コンパイル

dirコマンドでファイル一覧を表示すると「hello.c」のソースファイルが確認できます。

dir
hello.c

gccコマンドでコンパイルします。

gcc hello.c

dirコマンドでファイル一覧を表示して、a.exeという実行形式ファイルができていることを確認します。

a.exe  hello.c

プログラムの実行

a.exeと入力すると実行できます。

a.exe
Hello World!!

4. 分割コンパイル

複数のソースファイルから分割コンパイルして1つの実行形式ファイルする方法について見ていきます。

分割コンパイルの流れ

分割コンパイルの流れは以下のようになります。

  1. コーディング(ソースファイル作成)
  2. オブジェクトファイルの作成(単一ファイルのコンパイル)
  3. 実行形式ファイルの作成(オブジェクトファイルのリンク)

分割コンパイルの実施例

分割コンパイルの実施例です。

コーディング(ソースファイル作成)

以下の2つのソースファイルを作成します。

Main.c
#include <stdio.h>

void hello();

int main(void) {
        hello();
        return 0;
}
Hello.c
#include <stdio.h>

void hello() {
        printf("Hello World!!\n");
}

オブジェクトファイルの作成(単一ファイルのコンパイル)

それぞれのファイルをgccの-cオプションでコンパイルして.oファイルを作成します。

gcc -c Main.c
gcc -c Hello.c

実行形式ファイルの作成(オブジェクトファイルのリンク)

gccの-oオプションで2つのMain.oとHello.oファイルをリンクして実行形式ファイルを作成します。

gcc Main.o Hello.o -o sample.exe

サンプルの実行

作成したsample.exeを実行するとHello World!!と表示されます。

sample.exe
Hello World!!

5. ヘッダーファイルの作成方法

C言語のヘッダ―ファイルの作成方法について見ていきます。

ヘッダーファイルとは

ヘッダーファイルとは、関数のプロトタイプ宣言などの記述をまとめたファイルのことをいいます。 複数のソースファイルで同じ#include文を記述したりする場合に便利です。

ヘッダーファイルの使い方

#include文で「#include <stdio.h>」や「#include "hello.h"」のように記述して使用します。 標準ライブラリのヘッダーファイルは「<」「>」を使用し、ユーザ定義のヘッダーファイルは「"」「"」を使用してヘッダーファイルを指定します。

ヘッダーファイルの作成例

ヘッダーファイルの作成例です。

コーディング(ヘッダーファイルの作成)

まずは以下のヘッダーファイルを作成します。

sample.h
#ifndef SAMPLE_H
#define SAMPLE_H

#include <stdio.h>
void hello();

#endif

上記のように#include文や関数のプロトタイプ宣言などを記述します。 また、多くの場合、同じものを何度も読み込まないようにする工夫として、「#ifndef ~ #endif」マクロを使用します。

コーディング(ソースファイル作成)

以下の2つのソースファイルを作成します。

Main.c
#include "sample.h"

int main(void) {
        hello();
        return 0;
}
Hello.c
#include "sample.h"

void hello() {
        printf("Hello World!!\n");
}

オブジェクトファイルの作成(単一ファイルのコンパイル)

sample.hと同じフォルダにソースファイルを配置し、 それぞれのファイルをgccの-cオプションでコンパイルして.oファイルを作成します。

gcc -c Main.c
gcc -c Hello.c

実行形式ファイルの作成(オブジェクトファイルのリンク)

gccの-oオプションで2つのMain.oとHello.oファイルをリンクして実行形式ファイルを作成します。

gcc Main.o Hello.o -o sample.exe

サンプルの実行

作成したsample.exeを実行するとHello World!!と表示されます。

sample.exe
Hello World!!

6. 共有ライブラリの作成方法

共有ライブラリの作成方法を見ていきます。

共有ライブラリとは

実行形式ファイルのいつも使う処理などを分離して、他のプログラムでも使える共有ライブラリというファイルが作れます。

動的ライブラリ

実行時にリンクする共有ライブラリのことを動的ライブラリといいます。 Windowsの場合は.dll、Linuxの場合は.soといった拡張子をつけるのが一般的です。

動的ライブラリ

動的ライブラリの作成手順は以下です。

  1. コーディング(共有ライブラリ用のソースファイル作成)
  2. コンパイル(共有ライブラリ用のオブジェクトファイル作成)
  3. リンク(共有ライブラリ作成)
  4. コーディング(実行形式ファイル用のソースファイル作成)
  5. コンパイル(実行形式ファイル用のオブジェクトファイル作成)
  6. リンク(実行形式ファイル作成)
Windows環境(DLL)の例

Windows環境(DLL)の作成から実行までの例を見ていきます。

コーディング(共有ライブラリ用のソースファイル作成)

まずは以下のように「Hello World!!」と表示するhello.cを作成します。

// hello.c
#include "Hello.h"
void showHello() {
    printf("Hello World!!\n");
}

続いてそのヘッダファイルのhello.hを作成します。

#ifndef HELLO_H
#define HELLO_H

// ヘッダファイル
#include <stdio.h>

// 関数のプロトタイプ
void showHello();

#endif
コンパイル(共有ライブラリ用のオブジェクトファイル作成)

gccのcオプションを指定してコンパイルし、共有ライブラリ用のオブジェクトファイルを作成します。

gcc -c hello.c

※hello.oが作成されていることを確認します。

リンク(共有ライブラリ作成)

オブジェクトファイル(hello.o)と標準ライブラリなどを-sharedを指定してリンクして、共有ライブラリ(DLL)を作成します。

gcc hello.o -o hello.dll -shared

※hello.dllが作成されていることを確認します。

コーディング(実行形式ファイル用のソースファイル作成)

DLLの関数を呼び出すmain.cを作成します。

#include "Hello.h"
int main(void) {
	showHello();
}
コンパイル(実行形式ファイル用のオブジェクトファイル作成)

main.cをgccのcオプションを指定してコンパイルします。

gcc -c main.c
リンク(実行形式ファイル作成)

DLLを指定して実行形式ファイルを作成します。

gcc main.o hello.dll

※a.exeが作成されます。

サンプルの実行

作成したa.exeを実行するとHello World!!と表示されます。

a.exe
Hello World!!

※同じディレクトリにhello.dllがない場合実行できません。

7. その他のオプション

gccには上記に上げた以外にもオプションがあります。

-lws2_32オプション

-lws2_32は静的ライブラリのlibws2_32.aをリンクするためのオプションです。 コンパイルとリンクを分ける場合はリンク時に-lws2_32オプションを指定します。

コマンド例

コマンドの例です。

gcc sample1.c
gcc sample2.c
gcc sample1.o sample2.o -o sample.exe -lws2_32

Undefined Reference to WSAStartup@8

gccのリンク時に「Undefined Reference to `WSAStartup@'」というエラーが出力された場合は-lws2_32オプションが指定されているか確認しましょう。

undefined reference to `socket@12'

gccのリンク時に「undefined reference to `socket@12'」というエラーが出力された場合は-lws2_32オプションが指定されているか確認しましょう。

もっと知識を広げるための参考

更新履歴

戻る

スポンサーリンク

情報処理の知識体系

各試験の問題と解説

ランダム出題・採点アプリ

プログラミング

スポンサーリンク