【问题标题】:sql functions not found after include包含后找不到sql函数
【发布时间】:2018-05-19 20:06:46
【问题描述】:

我一直在 MacOSX 上用 c 语言编写一个基本的服务器/客户端程序,当我尝试将服务器链接到 mysql 数据库时,我遇到了严重的问题。我检查了 sql 头文件,它包含编译器找不到的所有函数声明。我下载了一个专门针对 x86_64 架构的连接器,使用它时出现了同样的错误。

考虑以下代码:

#include <mysql/mysql.h>
#include <mysql/my_global.h>

int main(int argc, char const *argv[]) {

   //Create the connector object
   MYSQL *con = mysql_init(NULL);
   if (con == NULL) {
     fprintf(stderr, "%s\n", mysql_error(con));
     exit(1);
   }

   //Connect to database
   if (mysql_real_connect(con, "localhost", "username","password", NULL, 0, NULL, 0) == NULL) {
     fprintf(stderr, "%s\n", mysql_error(con));
     mysql_close(con);
     exit(1);
   }
}  

编译时出现以下错误:

Undefined symbols for architecture x86_64:
   "_finish_with_error", referenced from:
   _main in ServerSocket-dbb1df.o
   "_mysql_close", referenced from:
   _main in ServerSocket-dbb1df.o
   "_mysql_error", referenced from:
   _main in ServerSocket-dbb1df.o
   "_mysql_init", referenced from:
   _main in ServerSocket-dbb1df.o
   "_mysql_query", referenced from:
   _main in ServerSocket-dbb1df.o
   "_mysql_real_connect", referenced from:
   _main in ServerSocket-dbb1df.o
   "_mysql_store_result", referenced from:
   _main in ServerSocket-dbb1df.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

任何关于这里出了什么问题的帮助将不胜感激!

【问题讨论】:

  • 你使用的是预编译头文件吗?
  • @Yunnosch 是的,我使用的是预编译头文件
  • @Cris Luengo 我确定我可以从哪里将库链接到标题。能详细点吗?
  • 如果您使用的是预编译头文件,您应该包含“stdafx.h”。请说明你在哪里做的。 (我假设您省略了该行以使您的代码示例更简洁。)包括它应该是第一个。

标签: c++ mysql c macos


【解决方案1】:

错误消息“ld: symbol(s) not found”表示您没有将库链接到程序中。

MySQL 文档,特别是 this page,解释了如何将您的程序与 MySQL 库链接:

mysql_config 显示编译或链接所需的选项:

shell> mysql_config --cflags
shell> mysql_config --libs

您可以运行这些命令来获取正确的选项并将它们手动添加到编译或链接命令中。或者,使用反引号将mysql_config 的输出直接包含在命令行中:

shell> gcc -c `mysql_config --cflags` progname.c
shell> gcc -o progname progname.o `mysql_config --libs`

如果您使用 C++(在您的问题中同时使用 C 和 C++ 作为标签),您当然希望将 gcc 替换为 g++,但也将 --cflags 替换为 --cxxflags

【讨论】:

  • 这解决了我的问题。 +1 简洁明了的答案
  • 因为在我的例子中,标志已经包含在 sql 标头中,gcc -o program progame.c mysql_config --libs 为我完成了这项工作。只是一种选择
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2018-02-28
  • 2014-12-02
  • 2018-10-15
  • 1970-01-01
相关资源
最近更新 更多