2016-01-24 18 views
-1

有沒有規則我不知道有關如何將包含實際實現的C頭文件鏈接到C++?在C++文件中使用僅C頭實現的未定義符號

我有一個僅包含頭文件的C文件,其中包含幾個函數的完整定義。當我將此文件包含在.cpp文件中,然後編譯時,鏈接器報告說該文件中指定的幾個函數未定義。

錯誤看起來是這樣的:

Undefined symbols for architecture i386: 
    "par_shapes_free_mesh(par_shapes_mesh_s*)", referenced from: 
     App::testgeo() in App.o 

的C文件有這個在它:

void par_shapes_free_mesh(par_shapes_mesh*); //forward declaration 

void par_shapes_free_mesh(par_shapes_mesh* mesh) 
{ 
    free(mesh->points); 
    free(mesh->triangles); 
    free(mesh->normals); 
    free(mesh->tcoords); 
    free(mesh); 
} 

顯然,功能其實是在定義。我將這個文件包含在我的App.cpp的頂部,然後使用par_shapes_free_mesh,但它會產生這個錯誤。我很困惑。

我嘗試以下伎倆,但它並沒有區別:

#ifdef __cplusplus 
extern "C" { 
#endif 

//and corresponding end brace 

這不得不提供相同的錯誤消息的有趣的效果,但名稱中帶有下劃線:

"_par_shapes_free_mesh", referenced from:

文件中也有這樣的typedef:

typedef struct par_shapes_mesh_s { 
    float* points; 
    int npoints; 
    uint16_t* triangles; 
    int ntriangles; 
    float* normals; 
    float* tcoords; 
} par_shapes_mesh; 

回答

4

爲了在編譯過程中包含定義,您需要在之前將#define PAR_SHAPES_IMPLEMENTATION添加到源文件,包括par_shapes.h

#define PAR_SHAPES_IMPLEMENTATION 
#include "par_shapes.h" 
+0

我想你會知道這一點,因爲你熟悉有問題的C庫?我從來沒有意識到我需要這個,我會嘗試。 – johnbakers

+0

不,從來沒有聽說過圖書館。但作爲Google的備份舞者並且知道合併可能需要明確包含定義,因此不難理解。 –

+0

好,謝謝,你釘了它。我學到了關於C庫的一些東西 – johnbakers