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

时间:2015-12-14 21:28:18

标签: c function codeblocks

所以我有一项任务,我认为我已经完成了。该程序应该能够使用Caesarchiffer加密或解密文件中的文本。所以我首先在一个.c文件中编码整个事件,然后将其拆分为两个.c文件和一个.h文件,并继续获取对'functionname'的未定义引用。

的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
}

我主要通过搜索得出的两个解决方案是,我在主要链接到func的地方做错了,或者我需要用我的编译器做一些我无法工作的东西

我正在使用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
}

2 个答案:

答案 0 :(得分:1)

首先在func.c中包含func.h

问题是您只编译main.c,因此编译器不知道加密函数的定义位置。您还需要编译func.c文件。

使用此命令

  

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

您可以查看以下答案: https://stackoverflow.com/a/18777608/1330198

答案 1 :(得分:1)

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

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

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