linux .c文件编写,linux上c/c++编程中的makefile文件编写

linux下c/c++编程中的makefile文件编写

在linux编程,使用文本编辑器是很通用的做法。对于单文件编译链接,使用简单的gcc或g++命令进行编译和链接。但是做大的项目不可能是一两个.c和.h文件能解决问题的,所以在进行多文件编译和链接时需要使用Makefile文件,让繁琐的工作变简单了。

在linux系统编写Makefile有两种常见的方法,一种是通过软件生成,主要是autoconf和automake软件。另一种是通过文本编辑器手动编写。这里主要说第二种方法。

手动编写Makefile文件的格式为:

target: prerequisites

(tab按键) command

例如:编写一个helloworld文件,中间的file.h文件如下:

#ifndef FILE_H

#define FILE_H

void print();

#endif

编写file.c文件如下:

#include

#include "file.h"

void print()

{

printf("Hello,World!\n");

}

编写helloworld.c的文件如下:

#include

#include "file.h"

int main(void)

{

print();

return 0;

}

进行单命令:

gcc -c helloworld.c

gcc -c file.c

gcc -o helloworld helloworld.o file.o

这样的话,如果文件比较多的话,就很麻烦了。

下面这是进行Makefile文件的编写:

helloworld: helloworld.o file.o

gcc -o $@ $^

.c.o:

gcc -c $<

这中间的$@代表目标文件

$^代表所有的依赖文件

$

当编写完这个Makefile文件之后,可以在终端中先跳到文件所在目录下,然后输入make。

之后就可以生成目标文件helloworld了。然后再终端中输入./helloworld运行程序。