我正在尝试用 C 语言编写一个小型 Web 应用程序,它使用
libpq
连接到 PostgreSQL。
我在 Debian 13 上安装了 libpq
,并使用以下 Makefile 来构建源代码:
CC = gcc
CFLAGS = -Wall -Wextra -pthread -Ithirdparty -I$(shell pg_config --includedir) -L$(shell pg_config --libdir) -l:$(shell pg_config --libdir)/libpq.so
SRCDIR = server
THIRDPARTY_DIR = thirdparty
SOURCES = $(wildcard $(SRCDIR)/*.c)
THIRDPARTY_SOURCES = $(wildcard $(THIRDPARTY_DIR)/*.c)
OBJS = $(SOURCES:.c=.o) $(THIRDPARTY_SOURCES:.c=.o)
TARGET = onio
$(TARGET): $(OBJS)
$(CC) $(CFLAGS) -o $(TARGET) $(OBJS)
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f $(OBJS) $(TARGET)
.PHONY: clean
看一下这一行:
CFLAGS = -Wall -Wextra -pthread -Ithirdparty -I$(shell pg_config --includedir) -L$(shell pg_config --libdir) -l:$(shell pg_config --libdir)/libpq.so
此 Makefile 后来扩展为如下内容:
gcc -Wall -Wextra -pthread -Ithirdparty -I/usr/include/postgresql -L/usr/lib/x86_64-linux-gnu -l:/usr/lib/x86_64-linux-gnu/pq.so.5.15 -o onio server/database.o server/dotenv.o server/http.o server/main.o server/request.o thirdparty/cJSON.o thirdparty/cJSON_Utils.o
我得到:
/usr/bin/ld: cannot find -l:/usr/lib/x86_64-linux-gnu/libpq.so: No such file or directory
collect2: error: ld returned 1 exit status
我去了
/usr/lib/x86_64-linux-gnu
,跑了ls *libpq*
。我得到了:
libpq.a libpq.so libpq.so.5 libpq.so.5.15
为什么 GCC 找不到这些现有的库?我也尝试过
libpq.a
,之前也尝试过-lpq
,但都没有成功。当我尝试 -lpq
(在 -I 和 -L 之后)时,我会得到:
database.c:(.text+0x75): undefined reference to `PQconnectdb'
/usr/bin/ld: database.c:(.text+0x8b): undefined reference to `PQstatus'
/usr/bin/ld: database.c:(.text+0x9e): undefined reference to `PQfinish'
明显有问题,但我无法找出错误所在。有谁知道这是怎么回事吗?
我尝试过
-lpq
、-l:/usr/lib/x86_64-linux-gnu/libpq.so
、-l:/usr/lib/x86_64-linux-gnu/libpq.a
等
查看 gcc 手册页,您可以找到以下选项:
-l library
Search the library named library when linking. (The second
alternative with the library as a separate argument is only
for POSIX compliance and is not recommended.)
The -l option is passed directly to the linker by GCC. Refer
to your linker documentation for exact details. The general
description below applies to the GNU linker.
The linker searches a standard list of directories for the
library. The directories searched include several standard
system directories plus any that you specify with -L.
在您的示例中,您已经使用
-L
指定了库的搜索路径,并且使用 -l
将在您已经放置的链接器路径中找到指定的库,因此您只需要执行 -lpq
此外,
libpq.so
已经在您的默认搜索路径中,因此在您的情况下,您不需要设置任何-L
。
gcc -o myapp myapp.c -lpq
注意: 在 Unix 世界中,
-l<name>
将在您的搜索路径中找到 lib<name>.a
或 lib<name>.so
。 AFAIK,默认搜索路径是 /lib/
和 /usr/lib
。 (在某些系统上可能是 /usr/local/lib
)。