在Xcode中使用C++,我尝试使用MySQL Connector/C++访问MySQL数据库。问题是该程序(用Xcode编译)总是崩溃
EXC_BAD_ACCESS (code=13, address=0x0)
打电话时
driver->connect(url, user, pass)
在Xcode中,我创建了一个完整的新项目(OS X>命令行工具),在main.cpp中插入了代码(见下文),添加了Boost和MySQL Connector头文件,包括路径以及libmysqlcppconn.6.1.1.1.dylib作为链接。库,然后单击运行按钮。
接下来的事情是,当我使用以下命令手动编译程序时
c++ -o test -I /usr/local/mysqlConnector/include/ -lmysqlcppconn main.cpp
该程序可以正常运行,并且还可以在表上运行INSERT语句。
程序代码摘自MySQL Connector/C++示例,即pthreads.cpp示例,但被截断为基本部分:
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <mysql_connection.h>
#include <mysql_driver.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
std::string url;
std::string user;
std::string pass;
std::string database;
/**
* Usage example for Driver, Connection, (simple) Statement, ResultSet
*/
int main(int argc, const char **argv)
{
sql::Driver *driver;
std::auto_ptr< sql::Connection > con;
url = "tcp://127.0.0.1:3306";
user = "appserver";
pass = "testpw";
database = "appserver";
try {
driver = sql::mysql::get_driver_instance();
/* Using the Driver to create a connection */
con.reset(driver->connect(url, user, pass));
con->setSchema(database);
sql::Statement* stmt = con->createStatement();
stmt->execute("INSERT INTO testtable (testnumber) values (5)");
} catch (sql::SQLException &e) {
return EXIT_FAILURE;
} catch (std::runtime_error &e) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
最佳答案
好,问题解决了。
这里的问题是一个编译标志。 MySQL Connector/C++的编译没有-stdlib=libc++
标志,但是Xcode将编译/链接标志添加到其命令中。这导致了崩溃。这也说明了手动编译程序为何起作用的原因,因为我没有在compile命令中包含该标志。
更清楚地说:我用-stdlib=libc++
标志重新编译了MySQL Connector/C++。然后Xcode编译的程序对我来说很好用。为了编译MySQL Connector/C++,我添加了
-DMYSQL_CXXFLAGS=-stdlib=libc++
安装连接器时需要运行的
cmake
命令。make VERBOSE=1
然后证明在编译连接器源时实际使用了该标志。