用makefile编译C项目

时间:2014-05-06 05:09:35

标签: c linux compilation compiler-errors makefile

我有一个名为reliability的目录:

ls reliability
analyze.c  appl.sh  constr.c  creer.c  greedys.c  Makefile

现在我想安装并编译它:

首先,Makefile的内容是:

CC = gcc
CFLAGS = -g -Wall -pthread

SRCS = constr.c creer.c analyze.c greedys.c
PROG = constr creer analyze greedys

all: $(PROG)

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

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

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

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

clean: 
        rm -f $(PROG)

当我开始编译时:

make -f Makefile 

发生错误:

gcc -g -Wall -pthread -o constr constr.c
/tmp/cca4NKQl.o: In function `main':
/home/t1/Desktop/reliability/constr.c:89: undefined reference to `exp'
/home/t1/Desktop/reliability/constr.c:89: undefined reference to `exp'
/home/t1/Desktop/reliability/constr.c:89: undefined reference to `pow'
/home/t1/Desktop/reliability/constr.c:89: undefined reference to `log'
collect2: ld returned 1 exit status
make: *** [constr] Error 1

我通过将-lm添加到gcc,

来传递这些错误

即使我将CFLAGSMakefile更改为CFLAGS = -g -Wall -pthread -lm,也会出现错误。

我的问题:

我现在应该单独编译所有.c程序吗?

谢谢,我真的需要帮助,

更新

编译creer.c时出现错误:

creer.c:39:10: warning: unused variable ‘val2’ [-Wunused-variable] creer.c:38:7:
               warning: unused variable ‘val’ [-Wunused-variable]

creer.c的一部分是:

void values(){
  int val;
  double val2;
  FILE *fp;
  fp = fopen("instances","r");
  fseek(fp,0,SEEK_SET);
  if(fscanf(fp,"%d",&p)==EOF){printf("EOF\n");}
  if(fscanf(fp,"%d",&m)==EOF){printf("EOF\n");}
  if(fscanf(fp,"%d",&K)==EOF){printf("EOF\n");}
  if(fscanf(fp,"%lf",&lambda_com)==EOF){printf("EOF\n");}
  if(fscanf(fp,"%d",&num_inst)==EOF){printf("EOF\n");}
  if(fscanf(fp,"%d",&boundl)==EOF){printf("EOF\n");}
  if(fscanf(fp,"%d",&boundp)==EOF){printf("EOF\n");}
  fclose(fp);
}

1 个答案:

答案 0 :(得分:1)

您需要将该链接器选项-lm添加到命令行的末尾。

做这样的事情:

LDFLAGS=-lm

...

constr: constr.c    
        $(CC) $(CFLAGS) -o constr constr.c $(LDFLAGS)

或者您可以定义模式规则:

%: %.c
        $(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)

并使用它来替换constr,creer等所有规则。