首页 > 解决方案 > 如何将 SQLite c 文件(合并)与 cpp 应用程序链接?

问题描述

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

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

我以这种方式将 sqlite3.h 包含在 main.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

如何静态链接这些文件?

标签: c++csqliteembedded-linuxstatic-linking

解决方案


您实际上并没有与 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 链接的文档中所指定的那样。


推荐阅读