Cpp-Mysql undefined引用'a function'错误

时间:2012-01-15 12:57:19

标签: c++ mysql

我有c ++代码连接并使用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和同样的错误。

我尝试了gcc -o test -L/usr/lib/mysql -lmysqlclient test.cpp,但这给了我以下错误:

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.hmysql_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函数时,我没有问题。还有其他方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

您需要使用g++编译和链接C ++代码,而不是gcc。否则,C ++标准库将无法正确链接。