未定义的引用;类公共函数在链接时不可访问

undefined reference to; class public function not accessible at link time

本文关键字:链接 访问 函数 引用 未定义      更新时间:2023-10-16

我正在尝试构建一个简单的程序,其中我定义了一个类并将其标头包含在 Main 中。在链接时,Linker 抱怨从类访问任何成员函数:

: undefined reference to voxel::anyFunction

即使函数是公共的并且包含标头。

最初我在创建体素对象时发现了这个问题 - 我重载了默认构造函数,但我发现体素类中的任何函数都存在问题。

以下是一些代码摘录:

voxel.hpp

class voxel
{
  public:
    //here defined some member variables
  //ommited the constructor
  void fillMemberValuesWithDummy();//sets all members to some dummy value
};

体素.cpp

#include "voxel.hpp"
void voxel::fillMemberValuesWithDummy()
{
  //does the assignment to member variables
}

主.cpp

#include <iostream>
#include <fstream>
using namespace std;
#include "voxel.hpp"
{
  voxel someVoxel;
  somevoxel.fillMemberValuesWithDummy();
}

我认为这是我在这里(不是)做的事情非常愚蠢,但你能告诉我什么吗?

您需要链接所有目标文件才能获取可执行文件。当你只有两个源文件时,你可以直接编译它们:

g++ -o myprog.exe Main.cpp voxel.cpp

当你想划分编译和链接并这样做时:

g++ -c -o Main.o Main.cpp
g++ -c -o voxel.o voxel.cpp
g++ -o myprog.exe Main.o voxel.o

随意创建一个适当的生成文件来生成此类命令。

如果您的操作系统不需要.exe,请将其删除。