如何为我的C项目创建一个makefile?

时间:2012-12-14 13:49:40

标签: c linux makefile

这是我的c项目,它简直是linux shell我在linux下运行这个程序 我想为我的程序make makefile。我想要简单的makefile 了解我如何才能成功?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/types.h>
#define BUFFER_SIZE 1<<16
#define ARR_SIZE 1<<16
void sig_had(int signo)
{
    puts ("This is my signal handling ..!");

}
void parse_args(char *buffer, char** args, 
                size_t args_size)
{
    char *buf_args[args_size]; 
    char **cp;
    char *wbuf;
    size_t i, j;

    wbuf=buffer;
    buf_args[0]=buffer; 
    args[0] =buffer;

    for(cp=buf_args; (*cp=strsep(&wbuf, " \n\t")) != NULL ;){
        if ((*cp != NULL) && (++cp >= &buf_args[args_size]))
            break;
    }

    for (j=i=0; buf_args[i]!=NULL; i++){
        if(strlen(buf_args[i])>0)
            args[j++]=buf_args[i];
    }
}

int main(int argc, char *argv[], char *envp[]){
    char buffer[BUFFER_SIZE];
    char *args[ARR_SIZE];

    int status;
    size_t nargs;
    pid_t child_pid;
    signal(SIGCHLD,sig_had);
    while(1){
        printf("COMMAND ");
        fgets(buffer,BUFFER_SIZE,stdin);
        parse_args(buffer, args, ARR_SIZE); 

            child_pid = fork();
        if (child_pid){

            child_pid = wait(status);

        } else {
            execvp(args[0], args);


        }
    }    
    return 0;
}

3 个答案:

答案 0 :(得分:5)

根本不需要任何Makefile。假设您的源文件存储为foo.c,只需运行

即可
make foo

默认的Makefile将启动,执行

cc foo.c -o foo

答案 1 :(得分:4)

好的......如果你想为此生成一个makefile,那么输入:

all: yourfilename.c
    gcc yourfilename.c -o yourexename

放入与.c文件相同的名为“Makefile”(无扩展名)的文件中。然后在该目录中运行make

注1:空格在Makefile中很重要,构建gcc ...的命令应为1 <tab>缩进

注2:这只是一个简单的例子,您可以(应该)使用您自己的标志修改构建命令。 -Wall将是一个很好的投入。

注3: Makefile是一个很大的话题。请务必阅读相关内容:http://www.gnu.org/software/make/manual/

答案 2 :(得分:2)

假设之前未配置make个设置,

# gcc to compile source files.
CC = gcc
# linker is also "gcc". may be something else with other compilers.
LD = gcc
# Compiler flags go here.
CFLAGS = -g -Wall
# Linker flags go here. 
LDFLAGS =
# list of generated object files.
OBJS = hello.o
# program executable file name.
EXEC = exec

all: $(EXEC)

# rule to link the program
$(EXEC): $(OBJS)
      $(LD) $(LDFLAGS) $(OBJS) -o $(EXEC)

hello.o: hello.c 
    $(CC) $(CFLAGS) -c hello.c

只要你只有.c文件创建一个可执行的二进制文件,你就不需要了。