如何将SQLite c文件(合并)与cpp应用程序链接?

How to link a SQLite c file (the Amalgamation) with cpp application?

本文关键字:cpp 应用程序 链接 合并 SQLite 文件      更新时间:2023-10-16

我想在不安装sqlite3 或 sqlite3-dev 的情况下在嵌入式 Linux 上构建此过程(我已经尝试安装它们并且成功了(。

我在目录中有 4 个文件:main.cpp sqlite3.c sqlite3.h 示例.db

我以这种方式将 sqlite3.h 包含在主.cpp

extern "C"{
#include "sqlite3.h"
}

然后我输入了这些命令:

gcc -c sqlite3.c -o sqlite3.o
g++ -c main.cpp -o main.o

已经到此为止了,然后我写了这个

g++ -o main.out main.o -L.

但我收到这些错误

main.o: In function `main':
main.cpp:(.text+0xf6): undefined reference to `sqlite3_open'
main.cpp:(.text+0x16d): undefined reference to `sqlite3_exec'
main.cpp:(.text+0x1c6): undefined reference to `sqlite3_exec'
main.cpp:(.text+0x1f7): undefined reference to `sqlite3_free'
main.cpp:(.text+0x25c): undefined reference to `sqlite3_exec'
main.cpp:(.text+0x299): undefined reference to `sqlite3_exec'
main.cpp:(.text+0x2ca): undefined reference to `sqlite3_free'
main.cpp:(.text+0x32f): undefined reference to `sqlite3_exec'
main.cpp:(.text+0x33b): undefined reference to `sqlite3_close'
collect2: error: ld returned 1 exit status

如何静态链接这些文件?

您实际上并没有链接到 SQLite 对象文件sqlite3.o

链接器不知道未显式指定的文件或库,因此您需要执行以下操作

,例如
g++ -o main.out main.o sqlite3.o

考虑到您遇到的另一个错误,您需要在编译链接时使用-pthread选项进行构建。

-L选项是添加一个路径,库搜索您使用-l(小写 L(选项命名的库。链接器不会自动搜索任何库或对象文件。您确实需要在链接时明确指定它们。

总而言之,像这样构建:

g++ -Wall -pthread main.cpp -c
gcc -Wall -pthread sqlite3.c -c
g++ -pthread -o main.out main.o sqlite3.o -ldl

请注意,我们现在还链接到dl库,如 Shawn 链接的文档中所述。