c++ - 在 C++ 项目中使用 C 代码

标签 c++ c

我想在我的 C++ 项目中使用此 C 代码: mysql.c :

/* Simple C program that connects to MySQL Database server*/
#include <mysql.h>
#include <stdio.h>
#include <string.h>

main() {
   MYSQL *conn;
   MYSQL_RES *res;
   MYSQL_ROW row;

   char *server = "localhost";
   char *user = "root";
   char *password = "rebourne"; /* set me first */
   char *database = "mydb";

   conn = mysql_init(NULL);

   /* Connect to database */
   if (!mysql_real_connect(conn, server,
         user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   /* send SQL query */
   if (mysql_query(conn, "show tables")) {
      fprintf(stderr, "%s\n", mysql_error(conn));
      exit(1);
   }

   res = mysql_use_result(conn);

   /* output table name */
   printf("MySQL Tables in mysql database:\n");
   while ((row = mysql_fetch_row(res)) != NULL)
      printf("%s \n", row[0]);

   /* close connection */
   mysql_free_result(res);
   mysql_close(conn);
}

它用 gcc 编译:

gcc -o output-file $(mysql_config --cflags) mysql.c $(mysql_config --libs)

但不适用于 g++ ..

你会怎么做?

编辑: 错误是: 退出(1);未在此范围内声明

最佳答案

首先要做的是:如果您向我们展示编译错误,可能会更有帮助。

话虽如此,我最初的直觉是建议:

extern "C"
{
    #include <mysql.h>
    #include <stdio.h>
    #include <string.h>
}

目前这是一个猜测,但如果没有实际的错误消息,这就是您将获得的最佳结果。

哦,也许将文件重命名为以 .cpp、.c++ 或 .C(大写)结尾会有所帮助。

关于c++ - 在 C++ 项目中使用 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2396467/

相关文章:

c++ - 是否可以从函数的循环中返回多个值? C++

c++ - HP Fortify 分析结果,system() 命令注入(inject)

c - 如何检查整数是偶数还是奇数?

c - 为什么这个C程序会显示这个结果?

c - 处理用户在 C 中输入的字符串(错误处理)

c++ - 为什么 std::set 没有 "contains"成员函数?

c++ - 无法 typedef std::chrono::microseconds 覆盖其定义以更改其基础类型

c++ - 为什么我可以将类而不是函数放在 .h 文件中而不会出现多重定义错误?

c - 在线法官 (CODECHEF) 中的错误答案

c - 如何将结构成员定义为其他成员的总和