此处的编译器必须为交叉编译器:
以test文件为例:
1、将现有的文件编译为动态库:
gcc -O -fPIC -shared -o libtest.so test.h test.c
2、将文件添加到项目路径:
将libtest.so文件和test.h文件复制到.pro文件同级目录
3、在.pro文件中添加代码:
LIBS += ./libtest.so
注意!! 交叉编译的话,需要在ARM板子的 /usr/lib 路经下
创建so库的软链接,不然提示找不到so库。
ln -s /home/root/libtest.so /usr/lib/libtest.so
4、在项目头文件添加:
extern "C"
{
#include "csdn.h"
}
由于是C函数,在C++项目中需要添加extern "C"
4、此后,就可以在项目源文件中直接调用test.h文件中的函数等内容。
源码 test.h
#ifndef __TEST_H
#define __TEST_H
#include <stdio.h>
int add_func(int a, int b);
#endif
源码 test.c
#include "test.h"
int result_func =0;
int add_func(int a, int b)
{
result_func = a+b;
printf("%s %d -> %d",__FILE__,__LINE__,result_func);
return a+b;
}
源码 .pro文件
#-------------------------------------------------
#
# Project created by QtCreator 2019-09-19T08:59:12
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = SoLibTest
TEMPLATE = app
DEFINES += X64___
#DEFINES += ARM___
contains(DEFINES,X64___){
LIBS += -L/home/fangxin/tt -ltest
} else {
}
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h \
../../tt/test.h
FORMS += mainwindow.ui
DISTFILES += \
../../tt/test.so
源码 .cpp 调用so库函数
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
int tt;
extern int result_func;
tt = add_func(2,3);
qDebug() << __FILE__<<__LINE__<< tt << result_func;
}
QT如何调用linux生成的so库
最新推荐文章于 2024-05-20 09:46:45 发布