声明和定义函数静态将产生“对function_name()的未定义引用”)>

问题描述 投票:0回答:2

这是在utils.hpp中定义的函数原型声明(NON OOP,所以不在任何类中)

static void create_xy_table(const k4a_calibration_t *calibration, k4a_image_t xy_table);

static void generate_point_cloud(const k4a_image_t depth_image,
                                 const k4a_image_t xy_table,
                                 k4a_image_t point_cloud,
                                 int *point_count);

static void write_point_cloud(const char *file_name, const k4a_image_t point_cloud, int point_count);

而且我在utils.cpp中有它们的定义,其中包括utils.hpp

当我在main中的main.cpp函数中调用使用任何函数时,出现以下错误:

/tmp/ccFcMfYB.o: In function `main':
main.cpp:(.text+0x208): undefined reference to 
`create_xy_table(_k4a_calibration_t const*, _k4a_image_t*)

编译命令:

g++ -o build/testtest src/main.cpp src/utils.cpp -I./include -lk4a

将所有函数都定义为非静态的,并且可以完美地进行编译!!

我对此一无所知。
  • 到底发生了什么?
  • 如果需要定义和链接静态函数,应该怎么做才能正确包含/链接?
  • 我的系统配置:gcc版本7.4.0(Ubuntu 7.4.0-1ubuntu1〜18.04.1)

    编辑

:这是我在utils.cpp中的函数定义:
static void create_xy_table(const k4a_calibration_t *calibration, k4a_image_t xy_table)
{
    k4a_float2_t *table_data = (k4a_float2_t *)(void *)k4a_image_get_buffer(xy_table);

    int width = calibration->depth_camera_calibration.resolution_width;
    int height = calibration->depth_camera_calibration.resolution_height;

    k4a_float2_t p;
    k4a_float3_t ray;
    int valid;

    for (int y = 0, idx = 0; y < height; y++)
    {
        p.xy.y = (float)y;
        for (int x = 0; x < width; x++, idx++)
        {
            p.xy.x = (float)x;

            k4a_calibration_2d_to_3d(
                calibration, &p, 1.f, K4A_CALIBRATION_TYPE_DEPTH, K4A_CALIBRATION_TYPE_DEPTH, &ray, &valid);

            if (valid)
            {
                table_data[idx].xy.x = ray.xyz.x;
                table_data[idx].xy.y = ray.xyz.y;
            }
            else
            {
                table_data[idx].xy.x = nanf("");
                table_data[idx].xy.y = nanf("");
            }
        }
    }
}

EDIT2

:这是我在main.cpp中所做的事情。
k4a_calibration_t calibration;
k4a_image_t xy_table = NULL;
/*
Calibration initialization codes here
*/
create_xy_table(&calibration, xy_table);

这是在utils.hpp中定义的函数原型声明(NON OOP,所以不在任何类中)静态void create_xy_table(const k4a_calibration_t * calibration,k4a_image_t xy_table);静态void ...

c++ g++ linker-errors
2个回答
4
投票

[将实现放入单独的编译单元(.cpp文件)时,当对象文件链接在一起时,您要求链接器稍后找到这些实现。当您将一个函数声明为static时,表示该函数在其他编译单元中不可见(这被称为static)。

现在,您包含带有internal linkage功能的标题。 static将获得其自己的副本,该副本对于所有其他编译单元不可见。 utils.cpp将仅看到声明,而看不到实现,因此将不会生成任何代码。这就是为什么出现链接错误的原因-代码在main.cpp中,但是任何人都无法访问。


0
投票

c / c ++中的静态修饰符将函数定义限制为一个编译单元(utils.cpp)。这些功能将无法通过其他编译单元查看/访问,例如您的情况下为main.cpp。

© www.soinside.com 2019 - 2024. All rights reserved.