libgit2 和 Qt 错误

libgit2 and Qt error

我想在 Qt 应用程序中使用 git。到目前为止,我使用 QProcess,但我不想使用它。所以我找到了 libgit2.

这按预期工作:

#include <QApplication>
#include "git2.h"
int main(int argc, char* argv[])
{
    git_repository* repo = 0;
    git_clone(&repo, "/path_to/barerep", "/path_to/test_clone", NULL);
    git_repository_free(repo);
    repo = 0;
}

但是在这里,git_clone 崩溃了。

int main(int argc, char* argv[])
{
    QApplication a(argc, argv);

    git_repository* repo = 0;
    git_clone(&repo, "/path_to/barerep", "/path_to/test_clone", NULL);
    git_repository_free(repo);
    repo = 0;

    return a.exec();
}

错误是: *** ‘/path_to/gittest’中的错误:free():无效指针:0x09d53a88 ***

有什么建议吗?当然,省略 QApplication 不是一个替代方案。没有return a.exec().

也会出现同样的错误

注意:实际上,有一个class GitRepository 有一个方法clone(const QString & url)(路径存储在class 的某处)。

同样有效

int main(int argc, char* argv[])
{
    GitRepository g;
    g.clone("path_to/barerep");
}

但事实并非如此。 (QObject!)

int main(int argc, char* argv[])
{
    QObject();  // <--
    GitRepository g;
    g.clone("path_to/barerep");
}

没有。

bool GitRepository::clone(const QString & url)
{
    git_repository* repo = 0;
    git_clone(&repo, CSTR(url), CSTR(path()), NULL);
    git_repository_free(repo);
    repo = 0;

    //loadFromTempDir();

    return true;
}

在第一个示例中用 QObject 替换 QApplication 可以抑制错误。

这种错误真的很难找到。我在将 Qt 库与其他库混合时也遇到了问题。诀窍是以一种编译单元中只包含一个库的方式组织代码。

创建一个class,环绕libgit2,并且只在这个class的cpp文件中包含libgit2头文件。不要在同一个文件中包含任何 qt 头文件。

仅参考 libgit 抛出你的包装器。当然,这看起来工作量很大,但结果是您的代码会更干净,这些神秘错误也会消失。

您需要在调用任何其他 libgit2 函数之前调用 git_libgit2_init()。正如文档所说:

This function must the called before any other libgit2 function in order to set up global state and threading.