[英]Declaring and defining function static yields “undefined reference to function_name()”
這是 utils.hpp 中定義的utils.hpp
原型聲明(非 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.cpp
中調用main
function 中的任何 function 時,我收到以下錯誤:
/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
將所有函數定義為非 static 並編譯完美! 我無法解決這個問題。
我的系統配置:gcc 版本 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)
編輯:這是我在 utils.cpp 中的 function 定義:
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
文件)時,您會要求 linker 稍后在對象文件鏈接在一起時找到這些實現。 當您將 function 聲明為static
,您說此 function 在其他編譯單元中不可見(這稱為內部鏈接)。
現在,您包含一個 header 和static
函數。 utils.cpp
將獲得它自己的副本,這對於所有其他編譯單元都是不可見的。 main.cpp
將只看到聲明,但看不到實現,因此不會生成任何代碼。 這就是您收到鏈接錯誤的原因 - 代碼位於utils.cpp
中,但任何人都無法訪問它。
如果您出於某種原因想要包含static
函數,您應該在 header 文件中提供它們的實現。 然后每個編譯單元將獲得它們自己的私有副本。
c/c++ 中的 static 修飾符將 function 定義限制為一個編譯單元 (utils.cpp)。 然后,在您的情況下,這些功能從其他編譯單元(例如 main.cpp)不可見/不可訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.