Home > Software engineering >  Qt: Shared C Library Exported From Golang
Qt: Shared C Library Exported From Golang

Time:12-03

I was doing some tests with Golang exporting shared libraries that can be used in C and came up with the following:

calcLib.go:

package main
import "C"

//export Calculator
func Calculator(x int, y int) int {
    return x y;
}

func main() {
    // Need a main function to make CGO compile package as C shared library
}

This simple library contains the Calculator that sums numbers. Now I've a small C program that will use it:

calc.c:

#include "calcLib.h"

int main() {     
    printf("Hello World from C!\n");     
    printf("Calculator() -> %d\n", Calculator(10,5));
    return 0;
}

Now I can compile the library and the C program with:

C:\Users\TCB13\Desktop
> go build -buildmode c-shared -o calcLib.a calcLib.go
C:\Users\TCB13\Desktop
> gcc -o calc.exe calc.c calcLib.a

This will output an executable that works as expected:

> .\calc.exe
Hello World from C!
Calculator() -> 15

Now, how can I use this shared library in a Qt project?

I tried to add the following to my .pro file:

LIBS  = -L"C:\Users\TCB13\shared\calcLib.a"
INCLUDEPATH  = "C:\Users\TCB13\shared"  # Shared folder includes the calcLib.h file

Then in my main.cpp:

#include "testapp.h"

#include <QApplication>
#include <QtDebug>
#include "calcLib.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    TestApp w;
    w.show();

    qDebug() << Calculator(10,5);

    return a.exec();
}

Compiling this results in the following errors:

enter image description here

How can I properly make/export/use this library in a Qt Application?

Here is my calcLib.h file for reference: https://pastebin.com/k3sKYiti

Thank you.

CodePudding user response:

In qmake project files LIBS variable uses same cli keys as gcc linker -L to specify searchpath for libraries and -l for library name (without lib prefix and without .a or .dll or .so suffix, I believe version with prefix should also work).

So it should be LIBS = -L$${PWD}\shared -lCalc

qmake-variable-reference

  • Related