问题描述
我有 C++ 代码可以连接并使用 mysql:
I have c++ code to connect to and use mysql:
#include <iostream>
#include <mysql/mysql.h>
using namespace std;
MYSQL *connection, mysql;
MYSQL_RES *result;
MYSQL_ROW row;
int query_state;
int main() {
mysql_init(&mysql);
connection = mysql_real_connect(&mysql,"localhost","root","pass","cpp_data",0,0,0);
if (connection == NULL) {
cout << mysql_error(&mysql) << endl;
return 1;
}
return 0;
}
当我编译时,我得到 test.cpp:(.text+0x11): undefined reference to 'mysql_init'
和 mysql_real_connect
和 相同的错误mysql_error
.
When I compile, I get test.cpp:(.text+0x11): undefined reference to 'mysql_init'
and the same error for mysql_real_connect
and mysql_error
.
我尝试过 gcc -o test -L/usr/lib/mysql -lmysqlclient test.cpp
,但这给了我以下错误:
I have tried gcc -o test -L/usr/lib/mysql -lmysqlclient test.cpp
, but this give me the following errors:
test.cpp:(.text+0x7a): undefined reference to `std::cout'
test.cpp:(.text+0x7f): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
test.cpp:(.text+0x87): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' etc.
我查了mysql.h
,mysql_real_connect
的定义是:
MYSQL * STDCALL mysql_real_connect(MYSQL *mysql, const char *host,
const char *user,
const char *passwd,
const char *db,
unsigned int port,
const char *unix_socket,
unsigned long clientflag);
我不用这些mysql函数就没有问题.有没有其他方法可以解决这个问题?
I have no problem when I don't use these mysql functions. Is there another option to solve this problem?
推荐答案
您需要使用 g++
而不是 gcc
来编译和链接 C++ 代码.否则 C++ 标准库将无法正确链接.
You need to compile and link C++ code with g++
, not gcc
. Otherwise the C++ standard libraries will not get linked properly.
这篇关于Cpp-Mysql 未定义对“函数"错误的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!