基本makefile程序:主要错误未定义引用“power”

时间:2017-02-23 19:41:10

标签: c makefile header

Header lab3p2.h

#ifndef LAB3P2_H
#define LAB3P2_H

long power(int integer1, int integer2);

#endif

电源功能:lab3p2f1.c

#include "lab3p2.h"
#include <stdio.h>

long power(int integer1, int integer2){ 
    int i;
    long ret =(long) integer1;
    if(integer2 ==0)
    {
          ret = 1;
    }else{
          for( i =1 ; i < integer2; i++)
          {
                ret = ret * integer1;
          }
    } 
   return ret;
}

主要:lab3p2.c

#include <stdio.h>
#include "lab3p2.h"
/*Takes in integers from the command line and returns the power function result*/
int main(int argc, char **argv){
     int a = atoi( *(argv+1));
     int b = atoi( *(argv+2));
     int c =atoi( *(argv+3));
     long functionResult;

     functionResult = power(b,c);               
     printf("The result of the power function is %ld \n", functionResult);
}

MakeFile:makefile

all: lab3p2
mkprog: lab3p2.o lab3p2f1.o
    gcc lab3p2.o lab3p2f1.o -o lab3p2
lab3p2.o: lab3p2.c
    gcc -ansi -pedantic -c lab3p2.c
lab3p2f1.o: lab3p2f1.c
    gcc -ansi -pedantic -c lab3p2f1.c
clean:
    rm -rf *.o lab3p2

为什么主要不能访问该功能? 我的编译方式有问题吗? 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您错过了目标lab3p2的规则;即mkprog应为lab3p2

all: lab3p2

lab3p2: lab3p2.o lab3p2f1.o
        gcc lab3p2.o lab3p2f1.o -o lab3p2

lab3p2.o: lab3p2.c
        gcc -ansi -pedantic -c lab3p2.c

lab3p2f1.o: lab3p2f1.c
        gcc -ansi -pedantic -c lab3p2f1.c

clean:
        rm -rf *.o lab3p2

使用您当前的Makefile,当您在不带参数的情况下运行make时,您将获得以下输出:

% make
gcc -ansi -pedantic -c lab3p2.c
cc   lab3p2.o   -o lab3p2
lab3p2.o: In function `main':
lab3p2.c:(.text+0x6b): undefined reference to `power'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'lab3p2' failed
make: *** [lab3p2] Error 1

make会尝试满足第一个目标(即all);这需要lab3p2。由于make无法找到显式规则来构建lab3p2,因此它会尝试隐式的 - 它知道可以通过将foo链接到程序中来构建foo.o;因此它运行命令

cc   lab3p2.o   -o lab3p2

但是,此命令不会链接到lab3p2f1.o定义power所在的位置。

这些隐含的规则对于简单的项目非常方便;例如,对于你的项目,GNU make的Makefile可以简单地写成

CC = gcc
CFLAGS = -ansi -pedantic

all: lab3p2

lab3p2: lab3p2.o lab3p2f1.o

clean:
        rm -rf *.o lab3p2

和make会自动弄清楚如何从相应的.o构建.c,并且它应该使用CC变量中的编译器,并传递CFLAGS中的参数}。