简体   繁体   English

C ++-包含库中的extern变量

[英]c++ - extern variable in included library

Even after quite a bit of googling, I have a problem in C++ where I made one project with a header and a source file and tried to make another project that included the first project. 即使经过大量的搜索,我在C ++中还是遇到了一个问题,即我使用头文件和源文件制作了一个项目,并试图制作另一个包含第一个项目的项目。 I found this question but in that the asker was able to generate a .a file which I cannot seem to do. 我发现了这个问题,但是问询者能够生成一个.a文件,但我似乎做不到。

Header.hpp 头文件

extern int num;

Source.cpp Source.cpp

#include "Header.hpp"

int num = 2;

(By the way, this is all in Code::Blocks) (顺便说一下,这一切都在Code :: Blocks中)

I made another project that would include the first project. 我做了另一个项目,其中包括第一个项目。

Main.cpp Main.cpp

#include <iostream> 

#include "Header.hpp"

int main(int argc, const char* argv[])
{
    std::cout << num << "\n";
}

To include the first project, I: 为了包括第一个项目,我:

  • Added the root directory of the first project to the "Search Directories" -> "Compiler" list of the second one 将第一个项目的根目录添加到第二个项目的“搜索目录”->“编译器”列表中

  • Added that same root directory of the first project to the "Search Directories" -> "Linker" list of the second one 将第一个项目的相同根目录添加到第二个项目的“搜索目录”->“链接器”列表中

When I try to compile this code with MinGW, I get an error: 当我尝试使用MinGW编译此代码时,出现错误:

undefined reference to 'num'

Some googling suggested that I add the .lib/.a file of the first project to the "Linker Settings" -> "Link Libraries" list. 一些谷歌搜索建议我将第一个项目的.lib / .a文件添加到“链接器设置”->“链接库”列表中。 However, my first project does not have a .lib/.a file and I am not quite sure how to create one. 但是,我的第一个项目没有.lib / .a文件,而且我不确定如何创建该文件。

What more is required to ensure that my "library" project can be included by my second project? 还需要什么来确保我的“图书馆”项目可以包含在我的第二个项目中?

Thanks to the comment by Sami Kuhmonen, I realized that the problem was that I had set the build target to an executable instead of a static library, which was why I was getting a .exe file instead of a .a file. 感谢Sami Kuhmonen的评论,我意识到问题在于我将构建目标设置为可执行文件而不是静态库,这就是为什么我要获取.exe文件而不是.a文件的原因。 All I had to do was change the build target, add the .a file to the "Linker Settings" -> "Link Libraries" list and change the "Search Directories" -> "Compiler"/"Linker" lists to search the include and src directories respectively and it worked. 我要做的就是更改构建目标,将.a文件添加到“链接器设置”->“链接库”列表,然后更改“搜索目录”->“编译器” /“链接器”列表以搜索包含文件。和src目录分别工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM