声明和定义函数静态产量 "undefined reference to function_name()"

Declaring and defining function static yields "undefined reference to function_name()"

这是 utils.hpp 中定义的函数原型声明(非 OOP,因此不在任何 class 中)

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.cpp 中调用 main 函数中的任何函数时,出现以下错误:

/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);

当您将实现放入单独的编译单元(.cpp 文件)时,您要求链接器稍后在 objects 文件链接在一起时找到这些实现。当您将函数声明为 static, you say that this function should not be visible in other compilation units (this is knows as internal linkage).

现在,您包含一个 header 和 static 函数。 utils.cpp 将获得自己的副本,这对所有其他编译单元都是不可见的。 main.cpp 只会看到声明,不会看到实现,因此不会生成任何代码。这就是您收到链接错误的原因 - 代码在 utils.cpp 中,但任何人都无法访问它。

如果您出于某种原因想要包含 static 函数,您应该在 header 文件中提供它们的实现。然后每个编译单元都会得到自己的私有副本。

static修饰符在c/c++中将函数定义限制为一个编译单元(utils.cpp)。这些函数不是来自其他编译单元的 visible/accessible,例如main.cpp 你的情况。