两个.c文件和一个.h文件,未定义的函数引用,c编程

Two .c files and one .h file, undefined reference to function, c programming

所以我有一个任务,我想我已经完成了。该程序应该能够使用 Caesarchiffer 加密或解密文件中的文本。所以我首先将整个代码编写在一个 .c 文件中,然后将其拆分为两个 .c 文件和一个 .h 文件,并且我不断得到对“函数名”的未定义引用。

main.c

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "func.h"

int main(){
int arrlen = 10, key = 1;
char * text1 = "text";
char * text2 = "text";
/*some code*/
encrypt(text1, arrlen, key, text2);
/*some code*/
decrypt(text1, arrlen, key, text2);
/*some code*/
}

func.h

#ifndef FUNC_H_INCLUDED
#define FUNC_H_INCLUDED

int encrypt(char *plainText, int arrLength, int key, char *cipherText);

int decrypt(char *plainText, int arrLength, int key, char *cipherText);

#endif

func.c

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int encrypt(char *plainText, int arrLength, int key, char *cipherText){
//do stuff
}
int decrypt(char *plainText, int arrLength, int key, char *cipherText){
//do stuff
}

我主要通过搜索提出的两个解决方案是,要么我在 link 函数的主要部分做错了,要么我需要用我的编译器做一些事情不要上班。

我正在使用 Code:Blocks 13.12 和 GCC 编译器。

当我在主文件中有函数和头文件时一切正常,所以我猜我需要对编译器做一些事情。 如果答案类似于

gcc main.c -o main.o -c

给我截图,无法运行。

我的代码全在main.c:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int encrypt(char *plainText, int arrLength, int key, char *cipherText);
int decrypt(char *plainText, int arrLength, int key, char *cipherText);

int main(){
int arrlen = 10, key = 1;
char * text1 = "text";
char * text2 = "text";
/*some code*/
encrypt(text1, arrlen, key, text2);
/*some code*/
decrypt(text1, arrlen, key, text2);
/*some code*/
}

int encrypt(char *plainText, int arrLength, int key, char *cipherText){
//do stuff
}
int decrypt(char *plainText, int arrLength, int key, char *cipherText){
//do stuff
}

首先在func.c

中包含func.h

问题是您只编译 main.c 所以编译器不知道在哪里定义了加密函数。你也需要编译 func.c 文件。

使用这个命令

gcc main.c func.c -o main.o -c

你可以查看这个答案:

当您将项目拆分为多个源文件(.c 文件)时,kaylum 回答得很好,您必须将它们全部编译成一个目标文件(.o 文件),然后编译器可以将您的目标文件合并到一个可执行文件。

未定义的引用错误意味着您的程序使用了尚未编译的内容。

gcc func.c main.c -o 此选项指定两个源文件将编译在同一个目标文件中,因此将引用您在程序中调用的函数。