c - 未定义的函数引用,使用 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);
}
}
解决方案
您应该使用-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
推荐阅读
- python - 如何从 c# 运行 python spaCy 脚本?
- python - 无法在 Python 中打开 NPY 文件
- aws-cdk - AWS CDK 高级构造与低级构造之间的区别
- r - 将数据框拆分为单独的并应用公式来计算 R 中段的转换
- google-oauth - 如何正确地将谷歌登录代码放入 nuxt 组件中
- java - 没有外键的 JPA OneToOne 关联不起作用
- java - RxJava 订阅相互依赖的 flowables 组合
- xcode - 如何在场景套件中显示金属质感
- solr - 如何使用 SOLR 中的类型字符串获取?
- django - Django Sendgrid Heroku 设置