【问题标题】:How to call C++ function from external file?如何从外部文件调用 C++ 函数?
【发布时间】:2015-04-21 03:24:57
【问题描述】:

我有 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): undefined reference to `fun(char)'

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

【问题讨论】:

    标签: c++ c header-files


    【解决方案1】:
    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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 你得到的错误是当你编译getch.cpp,而不是getch2.cpp(有fun)。
      猜你喜欢
      • 2014-02-11
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2012-08-24
      • 1970-01-01
      • 2021-05-07
      • 2013-09-15
      相关资源
      最近更新 更多