c++ 跨多个.cpp文件调用函数

c++ Calling functions across multiple .cpp files?

本文关键字:文件 调用 函数 cpp c++      更新时间:2023-10-16

我有 3 个文件:- 主要.cpp- 其他.cpp- 其他.h

我正在尝试从main.cpp调用在other.h中声明的函数,代码是用other编写的.cpp

我的代码:

主.cpp:

//#Allmyincludes
#include "other.h"
int main(int argc, const char *argv[])
{
    const char *file = argv[1];
    read(file);
    return 0;
}

其他.cpp:

//#Allmyincludes
#include "other.h"
void read(const char *file)
{
    //code
}

其他.h:

void read(const char *file);

我得到的错误是:

main.cpp:(.text+0x44): undefined reference to 'read(char const*)'

read() 中,我正在使用 main::variableName 从 main 内部访问变量(没有错误(,但是我只是无法让函数调用工作。如果我尝试做other::read(file);那也不起作用::因为它用于函数而不是文件。它给了我错误:'other' has not been declared.

非常感谢关于为什么我的头文件/调用不起作用的任何解释。

导致未定义引用错误的原因有很多。就您而言,根据您所描述的内容,最有可能的是您没有编译其他.cpp

您需要将 other.cpp 添加到您的项目/makefile/命令行中。

有关更详细的帮助,您可能需要解释如何构建程序。代码实际上没有任何问题,问题在于您构建程序的方式。

试试

gcc -墙主.cpp其他.cpp -o 我的主