2011-02-03 8 views
3

libdrm.hで定義した関数tester-1.cをlibdrm.cで実装しました。 3つのファイルは同じフォルダにあり、pthread関数を使用します。GCC:どうすればこのコンパイルとリンクができますか?

ファイルがある彼らの含まれます:

libdrm.h

#ifndef __LIBDRM_H__ 
#define __LIBDRM_H__ 

#include <pthread.h> 

#endif 

libdrm.c < - tehのメインを持っている - 何のメイン()

#include <stdio.h> 
#include <pthread.h> 
#include "libdrm.h" 

テスター-1.C <を持っていません()

#include <stdio.h> 
#include <pthread.h> 
#include "libdrm.h" 

libdrm.cのためのコンパイラエラーは言う:テスター-1.Cため

gcc libdrm.c -o libdrm -l pthread 
/usr/lib/gcc/x86_64-linux-gnu/4.4.5/../../../../lib/crt1.o: In function `_start': 
(.text+0x20): undefined reference to `main' 
collect2: ld returned 1 exit status 

とコンパイラのエラーは言う:

gcc tester-1.c -o tester1 -l pthread 
/tmp/ccMD91zU.o: In function `thread_1': 
tester-1.c:(.text+0x12): undefined reference to `drm_lock' 
tester-1.c:(.text+0x2b): undefined reference to `drm_lock' 
tester-1.c:(.text+0x35): undefined reference to `drm_unlock' 
tester-1.c:(.text+0x3f): undefined reference to `drm_unlock' 
/tmp/ccMD91zU.o: In function `thread_2': 
tester-1.c:(.text+0x57): undefined reference to `drm_lock' 
tester-1.c:(.text+0x70): undefined reference to `drm_lock' 
tester-1.c:(.text+0x7a): undefined reference to `drm_unlock' 
tester-1.c:(.text+0x84): undefined reference to `drm_unlock' 
/tmp/ccMD91zU.o: In function `main': 
tester-1.c:(.text+0x98): undefined reference to `drm_setmode' 
tester-1.c:(.text+0xa2): undefined reference to `drm_init' 
tester-1.c:(.text+0xac): undefined reference to `drm_init' 
tester-1.c:(.text+0x10e): undefined reference to `drm_destroy' 
tester-1.c:(.text+0x118): undefined reference to `drm_destroy' 

これらのすべての機能がlibdrm.cで定義されている

これらのファイルをコンパイルしてリンクするためにgccコマンドを使用する必要はありますか?

+1

二重先頭アンダースコア(および単一の先頭アンダースコアと大文字の後に続く)は、実装のために予約されています。このような名前は自分では使わないでください。 – delnan

答えて

11

.cソースをobject filesにコンパイルするには、GCCの-cオプションを使用します。そして、あなたが必要なライブラリに対して、実行可能ファイルにオブジェクトファイルをリンクすることができます。一度にをリンクとをコンパイルを行う

gcc libdrm.c -c 
gcc tester-1.c -c 
gcc tester-1.o libdrm.o -o tester1 -lpthread 

、などの多くの他の人が示唆している、あまりにも正常に動作します。しかし、ビルドプロセスはこれらの段階の両方を必要とすることを理解することは良いことです。

翻訳モジュール(=ソースファイル)が互いにシンボルを必要としたため、ビルドに失敗しました。

  • libdrm.cは、main()機能を持たないため、実行可能ファイルを作成できませんでした。
  • tester-1.cのリンクには、libdrm.cで定義されている必要なシンボルが通知されなかったため、リンクできませんでした。

-cオプションを指定すると、GCCは、コンパイルしたソースをアセンブルしますが、ライブラリに実行ファイルにリンクまたはパッケージ化することができる.oファイル、とあなたを残して、リンクをスキップ。

1

すべてのソースファイルを個別に処理するのではなく、まとめてコンパイルする必要があります。いずれか、またはlibdrm.cをライブラリとしてコンパイルし、コンパイルするときにtester1.cとリンクします。

+0

また、libdrm.cをオブジェクトファイルとしてコンパイルし、それをリンクすることもできます。これは、 "one go"コンパイルがフードの下で行うことです。 –

1
gcc test-1.c libdrm.c -o libdrm -l pthread 
関連する問題