头文件中包含函数

Inluding functions in header file

本文关键字:函数 包含 文件      更新时间:2023-10-16

我有头文件:

dictionary.h:

#ifndef dictionary_h__
#define dictionary_h__
extern char *BoyerMoore_positive(char *string, int strLength);
extern char *BoyerMoore_negative(char *string, int strLength);
extern char *BoyerMoore_skip(char *string, int strLength);
#endif

函数定义:dictionary.cpp

#include<stdio.h>
#include<string.h>
char *BoyerMoore_positive(char *string, int strLength)
{
} ---- //for each function

和主文件main.cpp:

#include "dictionary.h"
#pragma GCC diagnostic ignored "-Wwrite-strings"
using namespace std;
void *SocketHandler(void *);
int main(int argv, char **argc)
{ 
----
    skp = BoyerMoore_skip(ch[i], strlen(ch[i]) );
        if(skp != NULL)
        {
            i++;
            printf("inn");
            continue;
        }
        printf("n hi2 n");
        str = BoyerMoore_positive(ch[i], strlen(ch[i]) );
        str2= BoyerMoore_negative(ch[i], strlen(ch[i]) );
----
}

当我执行main.cpp 时

它给出:

/tmp/ccNxb1ix.o: In function `SocketHandler(void*)':
LinServer.cpp:(.text+0x524): undefined reference to `BoyerMoore_skip(char*, int)'
LinServer.cpp:(.text+0x587): undefined reference to `BoyerMoore_positive(char*, int)'
LinServer.cpp:(.text+0x5bd): undefined reference to `BoyerMoore_negative(char*, int)'
collect2: error: ld returned 1 exit status

我不知道为什么它找不到函数!感谢帮助!

您需要将两个源文件编译为main.odictionary.o,然后将这些对象文件链接到最终可执行文件中:

$ g++ -c main.cpp
$ g++ -c dictionary.cpp
$ g++ -o myexe main.o dictionary.o

或者你可以一次性构建和链接:

$ g++ -o myexe main.cpp dictionary.cpp 

你通常会创建一个Makefile来减轻这个过程的繁琐,它可能只有(未经测试的):

myexe: main.o dictionary.o

那么简单来说:

$ make

您确定您的dictionary.cpp包含在您的项目中并且构建时没有错误吗?编译后,Linker在对象文件中找不到这些函数,请查看完整的日志以了解dictionary.cpp文件的编译错误或成功。