如何从外部文件调用C++函数?

How to call C++ function from external file?

我有 3 个 C++ 源文件,我需要从一个文件调用一个函数到另一个文件

getch.cpp

#include<stdio.h>
#include "getch2.h"
main()
{
 char ch='x';
 fun(ch);   
}

getch2.cpp

#include<stdio.h>
void fun(char);
main()
{

}
void fun(char x)
{
printf("the ascii value of the char is %d",x);
}

func.h

void fun(char);

当我编译 getch2.cpp 时出现错误

C:\Users\amolsi\AppData\Local\Temp\cc1k7Vdp.o getch.cpp:(.text+0x18): 未定义对`fun(char)'的引用

C:\Users\amolsi\Documents\C files\collect2.exe [错误] ld 返回 1 退出状态

你的 #include 很好,问题是你没有在任何地方实现 fun

  1. 您的 main 函数需要更改为:

    int main() { ... }
    
  2. getch.cppgetch2.cpp 都包含 main 函数。您不能将它们一起使用以形成可执行文件。它们必须用于创建单独的可执行文件。

  3. 为了让您使用 getch.cppgetch2.cpp 中的 fun 来构建可执行文件,您需要将 void fun(char){...} 的定义从getch2.cpp 到另一个 .cpp 文件。我们称它为 func.cpp.

  4. 使用getch.cppfunc.cpp构建一个可执行文件。

  5. 使用 getch2.cppfunc.cpp 构建另一个可执行文件。

更新,回应OP的评论

文件func.h:


void fun(char);

文件func.cpp:


void fun(char x)
{
   printf("the ascii value of the char is %d",x);
}

文件getch.cpp:


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

int main()
{
   char ch='x';
   fun(ch);
   return 0;
}

文件getch2.cpp:


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

int main()
{
   char ch='y';
   fun(ch);
   return 0;
}

使用 getch.cppfunc.cpp 构建可执行文件 getch.exe
使用 getch2.cppfunc.cpp 构建可执行文件 getch2.exe