简体   繁体   中英

libgit2 and Qt error

I want to use git from an Qt application. So far, I use QProcess, but I do not want to use that. So I found libgit2.

This works as expected:

#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;
}

But here, git_clone crashes.

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();
}

The error is: *** Error in `/path_to/gittest': free(): invalid pointer: 0x09d53a88 ***

Any suggestions? Of course, omitting QApplication is not an alternative. The same error occurs without return a.exec() .

Note: Actually, there is a class GitRepository with a method clone(const QString & url) (the path is stored somewhere in the class).

Again, this works

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

But this does not. (QObject!)

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

does not.

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;
}

Replacing QApplication by QObject in the first example suppresses the error.

You need to call git_libgit2_init() before calling any other libgit2 functions. As the documentation says:

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

These kind of errors are really hard to find. I also had problems mixing Qt libraries with other libraries. The trick is to organize your code in a way that there is only one library included in one compilation unit.

Create a class, which wraps around libgit2, and only include the libgit2 headers in the cpp file of this class. Do not include any qt headers in the same file.

Only refer to libgit throw your wrapper. Sure it seems like a lot of work, but as a result your code will be cleaner, and these misterious errors will be gone.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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