I have a small piece of code which (should) allows me to connect to an MySQL database, here is the code:
#include <iostream>
#include <mariadb/mysql.h> // /usr/includes/mariadb/mysql.h
struct connection_details
{
const char *server, *user, *password, *database;
};
MYSQL* mysql_connection_setup(struct connection_details mysql_details){
MYSQL *connection = mysql_init(NULL); // mysql instance
//connect database
if(!mysql_real_connect(connection, mysql_details.server, mysql_details.user, mysql_details.password, mysql_details.database, 0, NULL, 0)){
std::cout << "Connection Error: " << mysql_error(connection) << std::endl;
exit(1);
}
return connection;
}
// mysql_res = mysql result
MYSQL_RES* mysql_perform_query(MYSQL *connection, const char *sql_query){
//send query to db
if(mysql_query(connection, sql_query)){
std::cout << "MySQL Query Error: " << mysql_error(connection) << std::endl;
exit(1);
}
return mysql_use_result(connection);
}
int main(int argc, char const *argv[])
{
MYSQL *con; // the connection
MYSQL_RES *res; // the results
MYSQL_ROW row; // the results row (line by line)
struct connection_details mysqlD;
mysqlD.server = "localhost"; // where the mysql database is
mysqlD.user = "netser"; // the root user of mysql
mysqlD.password = "root"; // the password of the root user in mysql
mysqlD.database = "mydatabase"; // the databse to pick
// connect to the mysql database
con = mysql_connection_setup(mysqlD);
// assign the results return to the MYSQL_RES pointer
res = mysql_perform_query(con, "show tables");
std::cout << ("MySQL Tables in mysql database:") << std::endl;
while ((row = mysql_fetch_row(res)) !=NULL)
std::cout << row[0] << std::endl;
/* clean up the database result set */
mysql_free_result(res);
/* clean up the database link */
mysql_close(con);
return 0;
}
When I try to compile it using:
g++ connectdb.cpp -o output && ./output
I get the next few errors:
/usr/bin/ld: /tmp/ccDwpmw3.o: in function `mysql_connection_setup(connection_details)':
connectdb.cpp:(.text+0xf): undefined reference to `mysql_init'
/usr/bin/ld: connectdb.cpp:(.text+0x3c): undefined reference to `mysql_real_connect'
/usr/bin/ld: connectdb.cpp:(.text+0x6c): undefined reference to `mysql_error'
/usr/bin/ld: /tmp/ccDwpmw3.o: in function `mysql_perform_query(st_mysql*, char const*)':
connectdb.cpp:(.text+0xc4): undefined reference to `mysql_query'
/usr/bin/ld: connectdb.cpp:(.text+0xef): undefined reference to `mysql_error'
/usr/bin/ld: connectdb.cpp:(.text+0x125): undefined reference to `mysql_use_result'
/usr/bin/ld: /tmp/ccDwpmw3.o: in function `main':
connectdb.cpp:(.text+0x1ca): undefined reference to `mysql_fetch_row'
/usr/bin/ld: connectdb.cpp:(.text+0x213): undefined reference to `mysql_free_result'
/usr/bin/ld: connectdb.cpp:(.text+0x21f): undefined reference to `mysql_close'
{By the way, I use Parrot OS with Mariadb and use VSCode}
I have never worked with databases in C++ before, so I have barely any idea what could be the problem, but I can assure you that the database does exit and that the connection to mysql.h has no problems...
The problem was how I was executing it, I had to use
g++ connectdb.cpp -o output -L/usr/include/mariadb/mysql -lmariadbclient
And not
g++ connectdb.cpp -o output
For future people with the same problem, here's a breakdown:
g++ connectdb.cpp -o output (normal compile)
-L/usr/include/mariadb/mysql (depending on what OS you have and if you use mariadb, you may have to change this to something like -L/usr/include/mysql instead, if you do use mariadb and still have a problem, remember to apt-get install libmariadb-dev)
-lmariadbclient (You have to apt-get install mariadb... If you're using MySQL, use -lmysqlclient instead)
Related
I am working on my coursework for my university. It consists on making a database in c++. I have those errors from Monday and I can not solve them.
Can anyone help me to fix this issue, please?
I am working in VSCode and I am a beginner in c++, thank you.
code:
#include <stdio.h>
#include <D:\SSD\Desctop\barethika\sqlite3.h>
int main(int argc, char* argv[]) {
sqlite3 *db;
char *zErrMsg = 0;
int rc;
rc = sqlite3_open("test.db", &db);
if( rc ) {
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
return(0);
} else {
fprintf(stderr, "Opened database successfully\n");
}
sqlite3_close(db);
}
ERRORS:
c:\users\name\AppData\Local\Temp\ccguCZxk.o:tempCodeRunnerFile.cpp(.text+00xa4)
undefined reference to 'sqlite3_open'
c:\users\name\AppData\Local\Temp\ccguCZxk.o:tempCodeRunnerFile.cpp(.text+00xa4)
undefined reference to 'sqlite3_errmsg'
c:\users\name\AppData\Local\Temp\ccguCZxk.o:tempCodeRunnerFile.cpp(.text+00xa4)
undefined reference to 'sqlite3_close' collect2.exe:error: ld returned
1 exit status
Try to set the absolute path of the library. This kind of problem is usually the wrong path of the library
As it is my first question on the forum, please be forgiving with style issues.
I've been looking for information to solve this but the problem hasn't reached a solution. I ask here in the hope someone will know. In need of implementing a MySQL database inside a C++ environment, I've followed the steps in this video, about how to setup MySQL in such a way. However, when trying to build the simple .cpp used there I've been unable to achieve in making it work. From what I have been reading, I can tell my errors are related to the linker, but I do not know how to correct them.
It may not be important, but note that I use Eclipse in contrast to the person of the video, that works with Visual Studio.
Error from console:
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:15: undefined reference to `mysql_init#4'
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:17: undefined reference to `mysql_real_connect#32'
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:24: undefined reference to `mysql_query#8'
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:27: undefined reference to `mysql_store_result#4'
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:28: undefined reference to `mysql_fetch_row#4'
C:\Users\quimi\Desktop\eclipse\AskACountryC++\Debug/../MySqlTest.cpp:35: undefined reference to `mysql_error#4'
The project's Include paths in GCC C++ Compiler:
"C:\Program Files\MySQL\MySQL Server 8.0\include"
"C:\Program Files\MySQL\Connector C++ 8.0\include"
The Libraries in MinGW C++ Linker:
:libmysql.lib
:mysqlcppconn.lib
And the Library search path in MinGW C++ Linker:
"C:\Program Files\MySQL\MySQL Server 8.0\lib"
"C:\Program Files\MySQL\Connector C++ 8.0\lib64\vs14"
Any idea about what can be happening and what could be a solution? Anything would be appreciated.
The .cpp:
#include <mysql.h>
#include <iostream>
using namespace std;
int qstate;
int main()
{
MYSQL* conn;
MYSQL_ROW row;
MYSQL_RES *res;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "localhost", "root", "password", "testdb", 3306, NULL, 0);
if (conn) {
puts("Successful connection to database!");
string query = "SELECT * FROM test";
const char* q = query.c_str();
qstate = mysql_query(conn, q);
if (!qstate)
{
res = mysql_store_result(conn);
while (row = mysql_fetch_row(res))
{
printf("ID: %s, Name: %s, Value: %s\n", row[0], row[1], row[2]);
}
}
else
{
cout << "Query failed: " << mysql_error(conn) << endl;
}
}
else {
puts("Connection to database has failed!");
}
return 0;
}
I am using SQLPP11 for sql queries and results and SQLPP11-Connector-mysql to establish connection with database.
And compiling my program using
g++ -std=c++1y main.cpp -I ../date -lsqlpp-mysql -lmysqlclient -lboost_system -lpthread
And here is the sample code i am using.
bool db_connection()
{
auto config = std::make_shared<mysql::connection_config>();
config->user = "root";
config->password = "";
config->database = "test";
config->debug = true;
sqlpp::mysql::connection db(config);
try
{
sqlpp::mysql::connection db(config);
std::cout << "Database connection establish...!!\n";
std::cout << "Now executing a very simple select query in table using sqlpp11 \n";
const auto g = changestreet::Goals{};
for(const auto& row : db(select(all_of(g)).from(g).unconditionally()))
{
std::cerr << row.goalId << "\n";
std::cerr << row.goalName << "\n";
std::cerr << row.goalAmount << "\n";
}
}
catch (const sqlpp::exception& e)
{
std::cerr << "No such database exits, you'll need to create it. \n";
std::cerr << e.what() << std::endl;
return false;
}
return true;
}
And the errors are
/tmp/ccxRheKs.o: In function `db_connection_cs()':
main.cpp:(.text+0x39d): undefined reference to `sqlpp::mysql::connection::connection(std::shared_ptr<sqlpp::mysql::connection_config> const&)'
main.cpp:(.text+0x3c8): undefined reference to `sqlpp::mysql::connection::~connection()'
main.cpp:(.text+0x400): undefined reference to `sqlpp::mysql::connection::~connection()'
/tmp/ccxRheKs.o: In function `db_connection_nav()':
main.cpp:(.text+0x4bf): undefined reference to `sqlpp::mysql::connection::connection(std::shared_ptr<sqlpp::mysql::connection_config> const&)'
main.cpp:(.text+0x4ea): undefined reference to `sqlpp::mysql::connection::~connection()'
main.cpp:(.text+0x522): undefined reference to `sqlpp::mysql::connection::~connection()'
/tmp/ccxRheKs.o: In function `sqlpp::mysql::serializer_t::escape(std::string)':
main.cpp:(.text._ZN5sqlpp5mysql12serializer_t6escapeESs[_ZN5sqlpp5mysql12serializer_t6escapeESs]+0x2a): undefined reference to `sqlpp::mysql::connection::escape(std::string const&) const'
/tmp/ccxRheKs.o: In function `sqlpp::result_t<sqlpp::mysql::char_result_t, sqlpp::result_row_t<sqlpp::mysql::connection, sqlpp::field_spec_t<changestreet::Goals_::GoalId::_alias_t, sqlpp::integral, false, false>, sqlpp::field_spec_t<changestreet::Goals_::GoalName::_alias_t, sqlpp::text, true, false>, sqlpp::field_spec_t<changestreet::Goals_::GoalAmount::_alias_t, sqlpp::floating_point, true, false>, sqlpp::field_spec_t<changestreet::Goals_::GoalStartTime::_alias_t, sqlpp::day_point, true, false>, sqlpp::field_spec_t<changestreet::Goals_::GoalEndTime::_alias_t, sqlpp::day_point, true, false>, sqlpp::field_spec_t<changestreet::Goals_::GoalMonthlyContribution::_alias_t, sqlpp::floating_point, true, false>, sqlpp::field_spec_t<changestreet::Goals_::GoalStatus::_alias_t, sqlpp::text, true, false>, sqlpp::field_spec_t<changestreet::Goals_::UsersUserId::_alias_t, sqlpp::integral, true, false> > >::~result_t()':
main.cpp:(.text._ZN5sqlpp8result_tINS_5mysql13char_result_tENS_12result_ro
Here is the build logs of both the libraries on my 64 bit debian machine.
Finally, i have figured out the solution.
It was the problem with g++ version. Recent versions g++-5 and g++-6 have such problems, But when i get back to old g++ version 4.9.2 everything is running smooth.
"undefined reference to" usually means that the linker can not find the required library. Make sure your PATH environment has those libs sqlpp-mysql mysqlclient in scope.
I am successfully running opencv python code on raspberry pi 2 (raspbian).
Now I want to try to compile opencv C++ code on raspberry pi 2 by using this command:
g++ -std=c++0x test_colour_tracking_1.cpp -otest_colour
The C++ coding as below.
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
VideoCapture cap(0); //capture the video from web cam
if ( !cap.isOpened() ) // if not success, exit program
{
cout << "Cannot open the web cam" << endl;
return -1;
}
while (true)
{
Mat imgOriginal;
bool bSuccess = cap.read(imgOriginal); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
imshow("image",imgOriginal);
}
return 0;
}
But it show error as below.
/tmp/ccHcCqSm.o: In function `main':
test_colour_tracking_1.cpp:(.text+0x70): undefined reference to `cv::VideoCapture::VideoCapture(int)'
test_colour_tracking_1.cpp:(.text+0x7c): undefined reference to `cv::VideoCapture::isOpened() const'
test_colour_tracking_1.cpp:(.text+0xd8): undefined reference to `cv::VideoCapture::read(cv::Mat&)'
test_colour_tracking_1.cpp:(.text+0x150): undefined reference to `cv::_InputArray::_InputArray(cv::Mat const&)'
test_colour_tracking_1.cpp:(.text+0x164): undefined reference to `cv::imshow(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, cv::_InputArray const&)'
test_colour_tracking_1.cpp:(.text+0x1a4): undefined reference to `cv::VideoCapture::~VideoCapture()'
test_colour_tracking_1.cpp:(.text+0x1f0): undefined reference to `cv::VideoCapture::~VideoCapture()'
/tmp/ccHcCqSm.o: In function `cv::Mat::~Mat()':
test_colour_tracking_1.cpp:(.text._ZN2cv3MatD2Ev[_ZN2cv3MatD5Ev]+0x3c): undefined reference to `cv::fastFree(void*)'
/tmp/ccHcCqSm.o: In function `cv::Mat::release()':
test_colour_tracking_1.cpp:(.text._ZN2cv3Mat7releaseEv[cv::Mat::release()]+0x58): undefined reference to `cv::Mat::deallocate()'
collect2: ld returned 1 exit status
And I want to ask how to check frame rate per second?
Try to use the following command:
g++ -std=c++0x test_colour_tracking_1.cpp -o test_colour `pkg-config --cflags --libs opencv`
I have installed OpenSSL using sudo apt-get install openssl-dev. When I try to compile it using Netbeans it gives following errors. How can I fix this problem?
g++ -lssl -o dist/Debug/GNU-Linux-x86/cppapplication_2 build/Debug/GNU-Linux-x86/main.o -L/home/sercan/Desktop/openssl-0.9.8h-1-lib/lib
build/Debug/GNU-Linux-x86/main.o: In function `main':
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:46: undefined reference to `OPENSSL_add_all_algorithms_noconf'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:48: undefined reference to `ERR_load_crypto_strings'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:58: undefined reference to `d2i_PKCS12_fp'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:66: undefined reference to `ERR_print_errors_fp'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:72: undefined reference to `PKCS12_parse'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:76: undefined reference to `ERR_print_errors_fp'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:82: undefined reference to `PKCS12_free'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:96: undefined reference to `PEM_write_PrivateKey'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:104: undefined reference to `PEM_write_X509_AUX'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:108: undefined reference to `sk_num'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:114: undefined reference to `sk_value'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:114: undefined reference to `PEM_write_X509_AUX'
/home/sercan/NetBeansProjects/CppApplication_2/main.cpp:112: undefined reference to `sk_num'
My code is here:
#include <stdio.h>
#include <stdlib.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/pkcs12.h>
/* Simple PKCS#12 file reader */
int main(int argc, char **argv)
{
FILE *fp;
EVP_PKEY *pkey;
X509 *cert;
STACK_OF(X509) *ca = NULL;
PKCS12 *p12;
int i;
if (argc != 4) {
fprintf(stderr, "Usage: pkread p12file password opfile\n");
exit(1);
}
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
if (!(fp = fopen(argv[1], "rb"))) {
fprintf(stderr, "Error opening file %s\n", argv[1]);
exit(1);
}
p12 = d2i_PKCS12_fp(fp, NULL);
fclose(fp);
if (!p12) {
fprintf(stderr, "Error reading PKCS#12 file\n");
ERR_print_errors_fp(stderr);
exit(1);
}
if (!PKCS12_parse(p12, argv[2], &pkey, &cert, &ca)) {
fprintf(stderr, "Error parsing PKCS#12 file\n");
ERR_print_errors_fp(stderr);
exit(1);
}
PKCS12_free(p12);
if (!(fp = fopen(argv[3], "w"))) {
fprintf(stderr, "Error opening file %s\n", argv[1]);
exit(1);
}
if (pkey) {
fprintf(fp, "***Private Key***\n");
PEM_write_PrivateKey(fp, pkey, NULL, NULL, 0, NULL, NULL);
}
if (cert) {
fprintf(fp, "***User Certificate***\n");
PEM_write_X509_AUX(fp, cert);
}
if (ca && sk_X509_num(ca)) {
fprintf(fp, "***Other Certificates***\n");
for (i = 0; i < sk_X509_num(ca); i++)
PEM_write_X509_AUX(fp, sk_X509_value(ca, i));
}
fclose(fp);
return 0;
}
you need to link to libcrypto as well - add -lcrypto to the link line and your code should link correctly.
natsu:~/openssl% gcc -o test test.c -L/usr/lib -lssl -lcrypto
links correctly, while:
natsu:~/openssl% gcc -o test test.c -L/usr/lib -lssl
/tmp/ccvA7iNe.o: In function `main':
test.c:(.text+0x4c): undefined reference to `OPENSSL_add_all_algorithms_noconf'
test.c:(.text+0x51): undefined reference to `ERR_load_crypto_strings'
test.c:(.text+0xb9): undefined reference to `d2i_PKCS12_fp'
test.c:(.text+0x103): undefined reference to `ERR_print_errors_fp'
test.c:(.text+0x133): undefined reference to `PKCS12_parse'
test.c:(.text+0x16a): undefined reference to `ERR_print_errors_fp'
test.c:(.text+0x180): undefined reference to `PKCS12_free'
test.c:(.text+0x22c): undefined reference to `PEM_write_PrivateKey'
test.c:(.text+0x266): undefined reference to `PEM_write_X509_AUX'
test.c:(.text+0x27b): undefined reference to `sk_num'
test.c:(.text+0x2b7): undefined reference to `sk_value'
test.c:(.text+0x2c9): undefined reference to `PEM_write_X509_AUX'
test.c:(.text+0x2d9): undefined reference to `sk_num'
collect2: ld returned 1 exit status
does not.