首页 > 解决方案 > 未定义的函数引用,使用 makefile 编译

问题描述

我目前正在处理一项作业,并尝试使用 makefile 对其进行编译,该文件目前如下所示:

all: myshell

myshell: main.o LineParser.o
    gcc -g -m32 -Wall -o main.o LineParser.o myshell

main.o: main.c
    gcc -g -m32 -Wall main.c -o main.o

LineParser.o: LineParser.c
    gcc -g -m32 -Wall LineParser.c -o LineParser.o

.PHONY: clean

clean: 
    rm -f *.c myshell

LineParser 包含一个 .c 文件和一个 .h 文件,并且我已将 .h 文件包含在我的 main.c 中,因此它应该可以正确编译。但是,我无法编译,因为我得到了“对‘parseCmdLines’和‘freeCmdLines’(LineParser 中的函数)的未定义引用。除了这两个函数之外,所有内容都可以使用当前的makefile正确编译,所以我相信问题出在在makefile中,但我不知道我需要改变什么。

主程序

#include "LineParser.h"
#include <stdio.h>
#include <unistd.h>

void execute(cmdLine *pCmdLine){
    int i = execv(pCmdLine->arguments[0],pCmdLine->arguments);
    if (i == -1)
        perror("Error: ");
}


int main (int argc , char* argv[], char* envp[])
{
    char cwd[MAX_ARGUMENTS];
    char userInput[2048];
    struct cmdLine * command;
    if (getcwd(cwd, sizeof(cwd)) == NULL)
        perror("getcwd() error");
    else
        printf("Current Working Directory is: %s\n", cwd);
    printf("Write a command:\n");
    if( fgets (userInput, 2048, stdin)!=NULL ) {
        command = parseCmdLines(userInput);
        freeCmdLines(command);
   }
}

标签: cmakefile

解决方案


您应该使用-c选项让 GCC 仅进行编译(创建目标文件,不链接来构建可执行文件)并-o使用选项来指定输出文件,而不是输入文件之一。

all: myshell

myshell: main.o LineParser.o
    # put -o at proper place
    gcc -g -m32 -Wall main.o LineParser.o -o myshell

main.o: main.c
    # add -c
    gcc -c -g -m32 -Wall main.c -o main.o

LineParser.o: LineParser.c
    # add -c
    gcc -c -g -m32 -Wall LineParser.c -o LineParser.o

.PHONY: clean

clean: 
    rm -f *.c myshell

推荐阅读