使用C ++库函数时未定义的引用

时间:2016-08-18 17:00:16

标签: c++ static-libraries codeblocks

使用Code :: Blocks和GNU GCC编译器,我一起创建了自己的库:

//main.cpp (Library)
int SampleAddInt(int i1, int i2)
{
    return i1 + i2;
}

将其编译为.a文件。然后我做了一个单独的项目来测试库函数。确保我在构建选项中正确链接它。这是我在我的项目中使用它的代码:

//main.cpp (Test Project)
#include <iostream>


using namespace std;

//Declaration of function from library
int SampleAddInt(int i1, int i2);

int main(){
    int x = SampleAddInt(2, 4);
    cout << x << "test" << endl;
}

尝试编译我的测试项目时出现此错误:

  

main.cpp | 9 |对“SampleAddInt(int,int)&#39; |

的未定义引用

由于某种原因,它似乎无法找到此功能。然后我包裹了外部&#34; C&#34; {...}在我的Test Project main.cpp源代码中声明并正确构建。

为什么,当我的库是从main.cpp源编译的时候,我是否需要使用extern&#34; C&#34;我的图书馆可以使用我的测试项目吗?为什么当我不使用extern&#34; C&#34;时,编译器是否告诉我该函数是未定义的引用?

1 个答案:

答案 0 :(得分:0)

搞定了。

问题在于它与Code :: Blocks有关。

它使用gcc编译器而不是g ++,所以如果我想运行任何库代码,我被迫使用extern“C”。

要解决此问题,我右键单击main.cpp,单击属性,然后将变量从“CC”更改为“CPP”,现在用g ++编译。

相关问题