C++ - 在main()函数中定义变量时遇到问题

use*_*896 6 c++ variables ogdf

我试图在C++,Visual Studio 2010中从外部库定义一个变量.它只有在我把它放在main函数之外时才有效.

此代码崩溃:

#include "StdAfx.h"
#include <ogdf\basic\Graph.h>
#include <ogdf\basic\graph_generators.h>

int main()
{
   ogdf::Graph g;
   ogdf::randomSimpleGraph(g, 10, 20);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

它给了我一个未经处理的例外:访问冲突.但是,如果它在main函数之外,它的工作没有任何问题:

#include "StdAfx.h"
#include <ogdf\basic\Graph.h>
#include <ogdf\basic\graph_generators.h>

ogdf::Graph g;

int main()
{
   ogdf::randomSimpleGraph(g, 10, 20);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

你有什么解决办法吗?我认为,这是由某种链接问题引起的.

编辑:看起来问题不是变量的初始化.当应用程序退出时,它会抛出异常.

int main()
{
ogdf::Graph g; // No problem
ogdf::randomSimpleGraph(g, 10, 20); // No problem
int i; // No problem
std::cin>>i; // No problem
return 0;    // Throws an exception after read i;
Run Code Online (Sandbox Code Playgroud)

}

调用堆栈: 打电话给STack

输出为:graphs.exe中的0x0126788f处的第一次机会异常:0xC0000005:访问冲突写入位置0x00000000.

graphs.exe中0x0126788f处的未处理异常:0xC0000005:访问冲突写入位置0x00000000.

gwi*_*rrr 5

适用于我的机器™.

像这样的深奥错误往往是二元不兼容的结果.基本上,由于不同的编译器/预处理器选项,您的代码和库"看到"的有效标头是不同的.

例如,如果您有一个包含以下标题代码的库:

class Foo
{
#ifdef FOO_DEBUG
    int debug_variable;
#endif
    int variable;
};
Run Code Online (Sandbox Code Playgroud)

图书馆功能:

void bar(Foo& foo)
{
    std::cout << foo.variable;
}
Run Code Online (Sandbox Code Playgroud)

和客户代码:

Foo foo;
foo.variable = 666;
bar(foo);
Run Code Online (Sandbox Code Playgroud)

如果FOO_DEBUG客户端和库之间没有同步,则可能会崩溃并烧毁 - variable将具有不同的预期偏移量.

在您的情况下,我怀疑以下之一可能是真的:

  • 您使用与代码不同的编译器构建了ogdf
  • 如果没有,你ogdf和你的代码有不同的构建配置(发布与调试)
  • 两者都是调试,但你已经定义了OGDF_DEBUG(这里推荐)
  • 您有不同的"结构成员对齐"设置