如何将一个函数从另一个文件调用到c中的main函数?

0 c qt

我正在使用qt并创建了ac项目.我创建了两个文件,一个头文件和源文件.我已经在头文件中声明了一个函数.所以我可以从main函数调用它.但是当我编译并运行时,我得到了"未定义的引用"错误.如何解决这个问题?我使用的是qt 5.5 ide.

我的代码:

头文件chapter_1.h

#ifndef CHAPTER_1_H
#define CHAPTER_1_H

//include all header files
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

/* function declaration */
int sum(int x, int y);

#endif // CHAPTER_1_H
Run Code Online (Sandbox Code Playgroud)

源文件

//include header files

#include "chapter_1.h"

int sum(int x, int y)
{
    int result = x+y;

    return result;
}
Run Code Online (Sandbox Code Playgroud)

主文件:

#include "chapter_1.h" 

int main()
{
    sum(23, 23);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

sel*_*bie 6

这不是编译器错误.这是一个链接器错误.您只需要将两个源文件(main.cpp和chapter1.cpp)都包含在项目中.