2017-02-21 6 views
2

は、私は3つのファイルC用のmakeファイルを作成して実行するには?

hellomain.c 
hellofunc.c 
helloheader.h 

を持っていると私はGCCコンパイラを経由して実行しています。通常、私は中に入力します。

gcc helloheader.h hellomain.c hellofunc.c -o results 

、すべて実行しますが。

これはどのようにしてメイクファイルに変換できますか?タイトルはmakefileです。コンパイラでmakeと入力して呼び出す必要があることはわかっています。しかし、makefileに実際に何を入力するかはわかりません。ただ、このようなあなたのだろう何かのようなプロジェクトのための最も簡単なメイクの可能な程度

+2

メイクファイルには数多くの例とチュートリアルがあります。より簡単なものからコピーして、そこから作業してください。 –

+0

また、実際にはヘッダーファイルを作成しないでください。 –

+0

私はここの例を試してみました:https://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html#zz-2.3しかし、それを動作させることができませんでした。 –

答えて

3

# The name of the source files 
SOURCES = hellomain.c hellofunc.c 

# The name of the executable 
EXE = results 

# Flags for compilation (adding warnings are always good) 
CFLAGS = -Wall 

# Flags for linking (none for the moment) 
LDFLAGS = 

# Libraries to link with (none for the moment) 
LIBS = 

# Use the GCC frontend program when linking 
LD = gcc 

# This creates a list of object files from the source files 
OBJECTS = $(SOURCES:%.c=%.o) 

# The first target, this will be the default target if none is specified 
# This target tells "make" to make the "all" target 
default: all 

# Having an "all" target is customary, so one could write "make all" 
# It depends on the executable program 
all: $(EXE) 

# This will link the executable from the object files 
$(EXE): $(OBJECTS) 
    $(LD) $(LDFLAGS) $(OBJECTS) -o $(EXE) $(LIBS) 

# This is a target that will compiler all needed source files into object files 
# We don't need to specify a command or any rules, "make" will handle it automatically 
%.o: %.c 

# Target to clean up after us 
clean: 
    -rm -f $(EXE)  # Remove the executable file 
    -rm -f $(OBJECTS) # Remove the object files 

# Finally we need to tell "make" what source and header file each object file depends on 
hellomain.o: hellomain.c helloheader.h 
hellofunc.o: hellofunc.c helloheader.h 

それはさらに簡単かもしれないが、これであなたはある程度の柔軟性を持っています。これは、基本的にはすでにコマンドラインでやっているやっている

results: hellomain.c hellofunc.c helloheader.h 
    $(CC) hellomain.c hellofunc.c -o results 

:ちょうど完全のために


が、これはおそらく、可能な限り最も簡単なメイクファイルです。これはあまり柔軟ではなく、ファイルが変更された場合はすべてを再構築します。

+0

これは、拡張子なしでmakefileにテストするためにここに投稿した最も基本的なバージョンを貼り付けたものです。しかし、makeとタイプしてEnterキーを押すと、区切り記号が見つかりません。やめる。 –

+0

@DanielDコマンドの前のスペースは* tabs *でなければなりません。それは例えば次のようなものではない。 4つのスペース。ファイルを編集して、タブであることを確認する必要があります。 –

+0

ああ、それを読んで忘れて、あまりにも忘れてしまった!ありがとう、これは私がこれで構築することができます: –

-1

ここには、ハードコードされたファイル名のmakefileがあります。フォローするのは簡単ですが、ソースファイルとヘッダーファイルを追加/削除すると更新が面倒かもしれません。

results: hellomain.o hellofunc.o 
    gcc $^ -o results 

hellomain.o: hellomain.c helloheader.h 
    gcc -c $< 

hellofunc.o: hellofunc.c helloheader.h 
    gcc -c $< 

メークファイルの字下げには必ずタブ文字を使用してください。

+0

これは、Makefileを書く方法の良いデモンストレーションではありません。 – duskwuff

+0

なぜそれは良くありませんか? – anatolyg

関連する問題