QT creator 12.0.2 Based on QT 6.6.0 windows 10
windows git bash 输出的各个文件名 test 是自己的测试用的静态库 target 是可执行文件项目 libtest.a 已经生成了
[pj]$ ls target/* target/main.cpp target/target.pro target/target.pro.user target/widget.cpp target/widget.h target/widget.ui [pj]$ ls test/* test/test.cpp test/test.h test/test.pro test/test.pro.user test/test_global.h [pj]$ ls build-test-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/* build-test-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/Makefile build-test-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/Makefile.Release build-test-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/Makefile.Debug build-test-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/debug: libtest.a test.o build-test-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/release: 以下是 test.pro, 我加了CONFIG += staticlib,现在在build-test-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/debug下只会生成 libtest.a ,不会生成 test.dll
QT -= gui TEMPLATE = lib DEFINES += TEST_LIBRARY CONFIG += c++17 # You can make your code fail to compile if it uses deprecated APIs. # In order to do so, uncomment the following line. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ test.cpp HEADERS += \ test_global.h \ test.h CONFIG += staticlib # Default rules for deployment. unix { target.path = /usr/lib } !isEmpty(target.path): INSTALLS += target 我在默认的 target.pro 中添加了如下内容用来链接 libtest.a
win32: LIBS += -L$$PWD/../build-test-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/debug/ -ltest INCLUDEPATH += $$PWD/../test DEPENDPATH += $$PWD/../test win32:!win32-g++: PRE_TARGETDEPS += $$PWD/../build-test-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/debug/libtest.a else:win32-g++: PRE_TARGETDEPS += $$PWD/../build-test-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/debug/libtest.a main.cpp
#include "widget.h" #include "test.h" #include <QApplication> int main(int argc, char *argv[]) { Test t; t.print(); // print 是 test 的 public 函数,用 qDebug 输出函数名 QApplication a(argc, argv); Widget w; w.show(); return a.exec(); } 编译报错 undefined reference, 应该是链接不到 libtest.a:
:-1: error: debug/main.o: in function `qMain(int, char**)': D:\Qt\pj\target\main.cpp:7: error: undefined reference to `__imp__ZN4TestC1Ev' :-1: error: D:\Qt\pj\build-target-Desktop_Qt_6_6_3_MinGW_64_bit-Debug/../target/main.cpp:8: undefined reference to `__imp__ZN4Test5printEv' :-1: error: collect2.exe: error: ld returned 1 exit status :-1: error: [Makefile.Debug:72: debug/target.exe] Error 1 不知道我是不是少了什么设置
如果以上描述不到位,这是两个项目的文件。先构建 test ,后运行 target https://drive.google.com/file/d/1FxtwscpdG9Atj2-YnAnR-CCKcmIwx0P7/view?usp=drive_link
