Cannot Open .png file with CImg on CLion (macOS) - c++

I've tried including libpng16/png.h and #define cimg_use_png, but none of them solved the error. Also, I have main.cpp, lenna.jpg and CImg.h in the same directory.
CMakeLists.txt:
cmake_minimum_required(VERSION 3.6)
project(HelloWorld)
set(CMAKE_CXX_STANDARD 17)
set(SOURCE_FILES main.cpp)
add_executable(HelloWorld ${SOURCE_FILES})
set(YOU_NEED_X11 1)
set(YOU_NEED_PNG 1)
if (${YOU_NEED_PNG} EQUAL 1)
message(STATUS "Looking for libpng...")
find_package(PNG REQUIRED)
include_directories(${PNG_INCLUDE_DIR})
target_link_libraries (HelloWorld ${PNG_LIBRARY})
target_compile_definitions(HelloWorld PRIVATE cimg_use_png=1)
endif()
if (${YOU_NEED_X11} EQUAL 1)
message(STATUS "Looking for X11...")
find_package(X11 REQUIRED)
include_directories(${X11_INCLUDE_DIR})
target_link_libraries(HelloWorld ${X11_LIBRARIES})
else()
target_compile_definitions(HelloWorld PRIVATE cimg_display=0)
endif()
main.cpp:
#include <iostream>
#include "CImg.h"
using namespace cimg_library;
int main() {
CImg<unsigned char> img("lenna.png");
int h = img.height();
int w = img.width();
int s = img.spectrum();
std::cout << "h: " << h << " w: " << w << " s: " << s << std::endl;
return 0;
}
The error:
[CImg] *** CImgIOException *** [instance(0,0,0,0,0x0,non-shared)] CImg<unsigned char>::load(): Failed to open file 'lenna.png'.
libc++abi.dylib: terminating with uncaught exception of type cimg_library::CImgIOException: [instance(0,0,0,0,0x0,non-shared)] CImg<unsigned char>::load(): Failed to open file 'lenna.png'.
Process finished with exit code 6

It looks like lenna.png is not being found. Relative paths are relative to the directory containing the executable. That means that if the executable is at cmake-build-debug/HelloWorld and you try to open lenna.png, the file at cmake-build-debug/lenna.png is opened. This means that you should either manually copy lenna.png into cmake-build-debug (I don't recommend this) or ask CMake to do it for you.
Add this to your CMakeLists.txt file.
add_custom_command(
TARGET HelloWorld POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${CMAKE_SOURCE_DIR}/lenna.png
${CMAKE_BINARY_DIR}/lenna.png
)
This will cause lenna.png to be copied into the same directory as your executable every time the executable is compiled.

Related

SDL2 program on windows cannot start (runnerw.exe: CreateProcess failed with error 193: %1)

I downloaded SDL2 release edition from: sdl-github: SDL2-devel-2.24.0-mingw.zip.
The OS is windows 10.
Compile environment is MINGW64.
IDE is clion.
My CMakeLists.txt file is
cmake_minimum_required(VERSION 3.20)
project(sdl_test)
set(CMAKE_CXX_STANDARD 20)
list(APPEND CMAKE_PREFIX_PATH "D:/lib/SDL2-2.24.0")
MESSAGE(STATUS "CMAKE_PREFIX_PATH: ${CMAKE_PREFIX_PATH}")
find_package(sdl2 CONFIG REQUIRED)
MESSAGE(STATUS "SDL2_INCLUDE_DIRS is ${SDL2_INCLUDE_DIRS}")
MESSAGE(STATUS "SDL2_LIBRARIES is ${SDL2_LIBRARIES}")
include_directories(${SDL2_INCLUDE_DIRS})
add_executable(sdl_test main.cpp)
target_link_libraries(sdl_test ${SDL2_LIBRARIES}-static)
target_link_libraries(sdl_test ${SDL2_LIBRARIES}main)
The main.cpp file is:
extern "C"{
#include <SDL.h>
};
#include <stdio.h>
int main(int argc, char* argv[])
{
SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO);
printf("SDL initialize ok!");
SDL_Quit();
getchar();
return 0;
}
The program can be compiled with no errors but when running it turns that:
runnerw.exe: CreateProcess failed with error 193: %1

C++: How to properly link compiled object using CMake in VSCode

OS
Windows 10
CMake: 3.16.3
Editor
VSCode: 1.48.1
Extensions
CMake Tools: 1.4.1
C/C++ 0.30.0-insiders3
Kit
Visual Studio Community 2019 Release - amd64
Project Repo
https://gitlab.com/NumeralRocket/kepler Removed, insufficient for minimal reproducible example
Tutorial
Introduction to Google Test and CMake
https://www.youtube.com/watch?v=Lp1ifh9TuFI
I'm attempting to build unit tests for one of my personal projects using CMake, and while I wholly admit I am quite new to CMake and a novice at C++, I am stumped on how to resolve this problem. When I go to build my project I get the following Linker error:
[main] Building folder: kepler
[build] Starting build
[proc] Executing command: "C:\Program Files\CMake\bin\cmake.EXE" --build n:/Unreal_Engine/Magellan/kepler/build-vscode --config Debug --target ALL_BUILD -- /maxcpucount:14
[build] Microsoft (R) Build Engine version 16.6.0+5ff7b0c9e for .NET Framework
[build] Copyright (C) Microsoft Corporation. All rights reserved.
[build]
[build] gmock.vcxproj -> N:\Unreal_Engine\Magellan\kepler\build-vscode\lib\Debug\gmockd.lib
[build] gmock_main.vcxproj -> N:\Unreal_Engine\Magellan\kepler\build-vscode\lib\Debug\gmock_maind.lib
[build] kepler.vcxproj -> N:\Unreal_Engine\Magellan\kepler\build-vscode\Debug\kepler.lib
[build] gtest.vcxproj -> N:\Unreal_Engine\Magellan\kepler\build-vscode\lib\Debug\gtestd.lib
[build] gtest_main.vcxproj -> N:\Unreal_Engine\Magellan\kepler\build-vscode\lib\Debug\gtest_maind.lib
[build] LINK : fatal error LNK1104: cannot open file 'Quaternion.lib' [N:\Unreal_Engine\Magellan\kepler\build-vscode\test\QuaternionTests.vcxproj]
[cmakefileapi-parser] Code model version (2.1) of cmake-file-api is unexpected. Expecting (2.0). IntelliSense configuration may be incorrect.
[cmakefileapi-parser] Code model version (2.1) of cmake-file-api is unexpected. Expecting (2.0). IntelliSense configuration may be incorrect.
[build] Build finished with exit code 1
For context, the project is structured as follows:
${ProjectRoot}
├── CMakeLists.txt
├── Quaternion.cpp
├── Quaternion.hpp
├── googletest
└── test
├── CMakeLists.txt
└── QuaternionTest.cpp
${ProjectRoot}/CMakeLists.txt
cmake_minimum_required(VERSION 3.16) # version can be different
set(CMAKE_VERBOSE_MAKEFILE ON)
set(This kepler)
get_filename_component(CODE_ROOT ${CMAKE_CURRENT_SOURCE_DIR} DIRECTORY)
project(${This}) #name of your project
project(${This} C CXX)
set(CMAKE_C_STANDARD 99)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
enable_testing()
add_subdirectory(googletest)
add_subdirectory(test)
set(Headers
Quaternion.hpp
)
set(Sources
Quaternion.cpp
)
add_library(${This} STATIC ${Sources} ${Headers})
${ProjectRoot}/Quaternion.cpp
#include <iostream>
#include "Quaternion.hpp"
// Default Constructor
Quaternion::Quaternion() {}
// Specified Value Constructor
Quaternion::Quaternion(double qs, double qi, double qj, double qk) : q0(qs), q1(qi), q2(qj), q3(qk) {}
Quaternion operator + (Quaternion const &quatA, Quaternion const &quatB) // 1) § 5.3
{
Quaternion quatC;
quatC.q0 = quatA.q0 + quatB.q0;
quatC.q1 = quatA.q1 + quatB.q1;
quatC.q2 = quatA.q2 + quatB.q2;
quatC.q3 = quatA.q3 + quatB.q3;
return quatC;
}
Quaternion operator - (Quaternion const &quatA, Quaternion const &quatB) // 1) § 5.3
{
Quaternion quatC;
quatC.q0 = quatA.q0 - quatB.q0;
quatC.q1 = quatA.q1 - quatB.q1;
quatC.q2 = quatA.q2 - quatB.q2;
quatC.q3 = quatA.q3 - quatB.q3;
return quatC;
}
void QuaternionLog(Quaternion quat2log)
{
std::cout << "q0: " << quat2log.q0 << std::endl;
std::cout << "q1: " << quat2log.q1 << std::endl;
std::cout << "q2: " << quat2log.q2 << std::endl;
std::cout << "q3: " << quat2log.q3 << std::endl;
}
int main()
{
Quaternion quat1;
Quaternion quat2(1, 2, 3, 4);
Quaternion quat3 = quat1 + quat2;
Quaternion quat4 = quat1 - quat2;
QuaternionLog(quat1);
QuaternionLog(quat2);
QuaternionLog(quat3);
QuaternionLog(quat4);
}
${ProjectRoot}/Quaternion.hpp
#ifndef QUATERNION_H
#define QUATERNION_H
class Quaternion
{
public:
double q0{ 1.0 };
double q1{ 0.0 };
double q2{ 0.0 };
double q3{ 0.0 };
Quaternion();
Quaternion(double qs, double qi, double qj, double qk);
friend Quaternion operator + (Quaternion const &quatA, Quaternion const &quatB);
friend Quaternion operator - (Quaternion const &quatA, Quaternion const &quatB);
};
#endif /* QUATERNION_H */
${ProjectRoot}/test/CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
set(This QuaternionTests)
set(Sources
QuaternionTest.cpp
)
add_executable(${This} ${Sources})
target_link_libraries(${This} PUBLIC
gtest_main
Quaternion
)
add_test(
NAME ${This}
COMMAND ${This}
)
${ProjectRoot}/test/QuaternionTest.cpp
#include <gtest/gtest.h>
#include "../Quaternion.hpp"
TEST(Quaternion, QuaternionConstructors)
{
Quaternion test_quat_1;
ASSERT_EQ(test_quat_1.q0, 1);
ASSERT_EQ(test_quat_1.q1, 0);
ASSERT_EQ(test_quat_1.q2, 0);
ASSERT_EQ(test_quat_1.q3, 0);
ASSERT_EQ(1,1);
};
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
};
How can I:
Ensure and Inspect that objects are being built appropriately?
Properly instruct CMake such that the linker can find my Quaternion (source code) object?
Any insight would be appreciated.
My mistake was in adding my library incorrectly:
${ProjectRoot}/CMakeLists.txt
cmake_minimum_required(VERSION 3.16) # version can be different
set(CMAKE_VERBOSE_MAKEFILE ON)
set(This kepler)
get_filename_component(CODE_ROOT ${CMAKE_CURRENT_SOURCE_DIR} DIRECTORY)
project(${This}) #name of your project
project(${This} C CXX)
set(CMAKE_C_STANDARD 99)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
enable_testing()
add_subdirectory(googletest)
add_subdirectory(test)
set(Headers
Quaternion.hpp
)
set(Sources
Quaternion.cpp
)
add_library(${This} STATIC ${Sources} ${Headers})
I was adding a library named ${THIS} which was "kepler" instead of the expected "Quaternion", so:
add_library(Quaternion STATIC ${Sources} ${Headers})
correctly tells the linker what/where to expect my library
AND
Leaving a main function in Quaternion.cpp, which was removed
Solution Source: vector-of-bool

c++ Linker error with static library

I am trying to include a static library that I have created with a static method but getting the following error in runtime when trying to invoke the method:
[ INFO] [1528271039.635221775]: Initializing nodelet with 4 worker threads.
/opt/ros/kinetic/lib/nodelet/nodelet: symbol lookup error:/catkin_ws/devel/lib//libmission_manager_nodelet.so: undefined symbol: _ZN14my_commons10ConsoleLog6ROSLogEiNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES6_
the static library has 2 files:
ConsoleLog.h:
#ifndef CONSOLE_LOG_H
#define CONSOLE_LOG_H
#include "ros/ros.h"
namespace my_commons
{
class ConsoleLog
{
public:
static void ROSLog(int type, std::string message,std::string taskName);
static void STDLog(int logType, std::string msg,std::string taskName);
};
} // namespace my_commons
#endif //CONSOLE_LOG_H
and ConsoleLog.cpp:
#include "ConsoleLog.h"
namespace my_commons
{
void ConsoleLog::ROSLog(int type, std::string message, std::string task)
{
switch (type)
{
case (0):
ROS_DEBUG_STREAM("########## " << task << " DEBUG: " << message << " ##########");
break;
case (1):
ROS_INFO_STREAM("########## " << task << " " << message << " ##########");
break;
case (2):
ROS_WARN_STREAM("########## " << task << " WARNNING: " << message << " ##########");
break;
case (3):
ROS_ERROR_STREAM("########## " << task << " ERROR: " << message << " ##########");
break;
}
}
void ConsoleLog::STDLog(int logType, std::string msg, std::string task)
{
std::cout << msg << std::endl;
}
} // namespace my_commons
the CMakelist.txt:
cmake_minimum_required(VERSION 2.8.3)
project(my_commons)
set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS}")
find_package(catkin REQUIRED COMPONENTS
roscpp
)
catkin_package(CATKIN_DEPENDS
INCLUDE_DIRS include)
include_directories(
${catkin_INCLUDE_DIRS}
include/
)
###########
## Build ##
###########
add_library(my_commons
src/ConsoleLog.cpp
)
## Specify libraries to link a library or executable target against
set_target_properties(my_commons PROPERTIES LINKER_LANGUAGE CXX)
target_link_libraries(my_commons
${catkin_LIBRARIES}
${roscpp_LIBRARIES}
)
#add_dependencies(name_of_package_nodelet)
install(DIRECTORY include/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
FILES_MATCHING PATTERN "*.h"
PATTERN ".svn" EXCLUDE)
# Install library
install(TARGETS my_commons
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
Edit:
Here is the clients CMakeLists.txt:
cmake_minimum_required(VERSION 2.8.3)
project(my_mission_manager)
set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS}")
find_package(catkin REQUIRED COMPONENTS
roscpp
nodelet
std_msgs
my_commons
message_runtime
std_srvs
)
catkin_package(
CATKIN_DEPENDS
message_runtime
std_msgs
my_commons
)
include_directories(
${catkin_INCLUDE_DIRS}
include/
)
###########
## Build ##
###########
add_library(my_mission_manager_nodelet
src/my_mission_manager_nodelet.cpp
)
## Specify libraries to link a library or executable target against
target_link_libraries( my_mission_manager_nodelet
${catkin_LIBRARIES}
${roscpp_LIBRARIES}
)
#add_dependencies(my_mission_manager_nodelet)
# Install library
install(TARGETS my_mission_manager_nodelet
ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
# Install header files
install(DIRECTORY src/
DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
)
# Install launch files
install(DIRECTORY launch/
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch
)
# Install xml files
install(FILES nodelet_plugins.xml
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}
)
What am I missing here?
By the way, I am able to use data from header files in my_commons (enums), the problem occurs when trying to add a cpp file an invoke a static method in it.
Thank you for your help!
Please find below a working example of correct CMake project:
Directory structure:
ROOT
|
+--inc
| +--ConsoleLog.hpp
+--src
| +--ConsoleLog.cpp
| +--main.cpp
+CMakeLists.txt
Your source and header files remains unchanged (I only changed *.h to *.hpp --> after all you write in C++, not C).
main.cpp:
#include "ConsoleLog.hpp"
int main() {
my_commons::ConsoleLog log;
log.ROSLog(1, "xxx", "yyy");
return 0;
}
CMakeLists.txt:
cmake_minimum_required(VERSION 2.8.11)
project(my_commons)
set(CMAKE_CXX_FLAGS "-std=c++11 ${CMAKE_CXX_FLAGS}")
find_package(catkin REQUIRED COMPONENTS roscpp)
add_library(my_commons STATIC src/ConsoleLog.cpp)
target_include_directories(my_commons PUBLIC inc ${roscpp_INCLUDE_DIRS})
target_link_libraries(my_commons ${catkin_LIBRARIES} ${roscpp_LIBRARIES})
add_executable(MyExec src/main.cpp)
target_link_libraries(MyExec my_commons)
Result of the execution:
./MyExec
[ INFO] [1528280295.971205050]: ########## yyy xxx ##########
I use newer CMake version to be able to use target_include_directories, because I like this feature. I changed your compiler flags to include C++11 standard, because apparently you use it. I also removed INSTALL CMake rules, because they are irrelevant to the question. Let me know if this answer is OK for you.
=============== EDIT(to answer OP comment)==============
Well, I don't have any problems with embedding this lib in another project structure. The error you got means that your directory structure is incorrect (my_commons dir doesn't exist). Your project tree should look like this:
ROOT
|
+--MyCommonsLib (this is the root of your my_commons library)
|
+--src
| +--main.cpp
+CMakeLists.txt
And your project's CMakeLists.txt might look like this:
cmake_minimum_required(VERSION 2.8.11)
project(SomeSimpleProjectUsingMyCommonsLib)
add_subdirectory(MyCommonsLib)
add_executable(MyExec src/main.cpp)
target_link_libraries(MyExec my_commons)
Just remember to remove the add_executable instruction from your MyCommonLib/CMakeLists.txt. Also main.cpp should be like this:
#include "ConsoleLog.hpp"
int main() {
my_commons::ConsoleLog::ROSLog(1, "xxx", "yyy");
return 0;
}
Sorry, before I didn't notice that ROSLog is declared as static.

allegro not working with clion (0xC000007B)

so I've hit a dead end, I'm simplying trying to run the following:
main.cpp:
#include <iostream>
#include <allegro5/allegro.h>
int main(int argc, char **argv) {
std::cout << "Hello, World!" << std::endl;
al_init();
std::cout << "hi" << std::endl;
return 0;
}
CMakeList.txt:
cmake_minimum_required(VERSION 3.6)
project(allegro_test)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp)
SET(ALLEGRO_ROOT C:/Users/duck-/workspace/cpp/recources/allegro/)
INCLUDE_DIRECTORIES( ${ALLEGRO_ROOT}/include )
LINK_DIRECTORIES( ${ALLEGRO_ROOT}/lib)
add_executable(allegro_test ${SOURCE_FILES})
TARGET_INCLUDE_DIRECTORIES(allegro_test PUBLIC ${ALLEGRO_ROOT})
TARGET_LINK_LIBRARIES(allegro_test allegro)
output:
"C:\Users\duck-\.CLion2016.2\system\cmake\generated\allegro test-50fbd97d\50fbd97d\Debug\allegro_test.exe"
Process finished with exit code -1073741701 (0xC000007B)
I'm using allegro-mingw-gcc6.2.0-x64-dynamic-5.2.2.zip from here and have copyied allegro-5.2.dll, cygintl-1.dll & cygintl-2.dll to
C:\Users\duck-.CLion2016.2\system\cmake\generated\allegro test-50fbd97d\50fbd97d\Debug\
where the program's executed. I've installed .NET Framework 4.6.2. Am I missing something? cheers in advance.
Since you are building the program in a Debug configuration, you'll need to include allegro-debug-5.2.dll, and not just allegro-5.2.dll.

Connecting to MySQL in C++

I am trying to learn C++ and I am having a bit of nightmare doing a test where I connect to a MySQL database.
I've had issues with the MySQL connector not linking properly then was getting issues related to relocation truncated to fitr_x86_64_32 against symbol.
I think I have fixed that by adding a compiler flag and now the app successfully builds and links.
When I run the app, it gets as far as calling get_driver_instance but then it exits. No exception is thrown, no errors nothing just exit code 0.
Below is my DBManager class
#include "DBConnectionManager.h"
using namespace std;
DBConnectionManager::DBConnectionManager() {
cout << "Starting DBConnectionManager - Updated" << endl;
try {
cout << "Getting driver instance" << endl;
driver = get_driver_instance();
cout << "Got driver instance" << endl;
conn = driver->connect("tcp://127.0.0.1:3306", "root", "password");
conn->setSchema("bugs");
cout << "Connected to database" << endl;
}
catch (SQLException ex) {
cout << "Error connecting to DB: " << ex.what() << endl;
}
catch (...) {
cout << "Something has gone wrong" << endl;
}
}
Below is the header file
#ifndef MYSQLTEST_DBCONNECTIONMANAGER_H
#define MYSQLTEST_DBCONNECTIONMANAGER_H
#include <driver.h>
#include <exception.h>
#include <resultset.h>
#include <statement.h>
using namespace sql;
class DBConnectionManager
{
private:
sql::Driver *driver;
sql::Connection *conn;
sql::Statement *statement;
sql::ResultSet *res;
public:
DBConnectionManager();
void performSql();
};
#endif //MYSQLTEST_DBCONNECTIONMANAGER_H
Below is my main method
#include "DBConnectionManager.h"
int main() {
DBConnectionManager dbConnectionManager;
dbConnectionManager.performSql();
return 0;
}
Below is my CMakeLists.txt file
cmake_minimum_required(VERSION 3.6)
project(MySQLTest)
include_directories("C:\\Program Files\\MySQL\\MySQL Connector C++ 1.1.7\\include\\cppconn" "C:\\Program Files\\MySQL\\MySQL Connector C++ 1.1.7\\lib\\opt")
SET(GCC_COVERAGE_LINK_FLAGS "-m64 -Wl,--image-base -Wl,0x10000000 -lpthread -pthread")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -m64 -Wl,--image-base -Wl,0x10000000 -lpthread -pthread ")
set(SOURCE_FILES main.cpp DBConnectionManager.cpp)
add_executable(MySQLTest ${SOURCE_FILES})
add_library(mysqlcppconn.lib)
set_target_properties(MySQLTest PROPERTIES LINKER_LANGUAGE CXX)
set_target_properties(mysqlcppconn.lib PROPERTIES LINKER_LANGUAGE CXX)
target_link_libraries(MySQLTest "C:\\Program Files\\MySQL\\MySQL Connector C++ 1.1.7\\lib\\opt\\mysqlcppconn.lib")
When I create the instance of my DBConnectionManager class it successfully calls the query and prints Starting DBConnectionManager - Updated followed by Getting Driver Instance but then it exits with Process finished with exit code 0 with no clues as to what went wrong.
Update
I'm finally getting somewhere. I found there are some MySQL client libraries within Cygwin so I have download them and referenced them in the cmake file.
My cmake file now looks like this:
cmake_minimum_required(VERSION 3.6)
project(MySQLTest)
SET(CPPCONN_PUBLIC_FUNC=)
SET(GCC_COVERAGE_LINK_FLAGS "-g -m64 -DCPPCONN_PUBLIC_FUNC= -Dmysqlcppconn_EXPORTS -lpthread -pthread -Wl,--image-base -Wl,0x10000000 -lz")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DCPPCONN_PUBLIC_FUNC= -Dmysqlcppconn_EXPORTS -std=c++11 -g -m64 -Wl,--image-base -Wl,0x10000000 -lpthread -pthread -lz")
include_directories("C:/mysql_connector/include")
include_directories("C:/boost_1_61_0")
set(BOOST_INCLUDE_DIR C:/boost_1_61_0)
set(BOOST_LIBRARY_DIR C:/boost_1_61_0/libs)
set(SOURCE_FILES main.cpp DBConnectionManager.cpp)
add_executable(MySQLTest ${SOURCE_FILES})
find_package(Boost COMPONENTS REQUIRED)
link_directories(C:/mysql_connector/lib)
target_link_libraries(MySQLTest "C:/mysql_connector/lib/mysqlcppconn.dll" "C:/Program Files/MySQL/MySQL Server 5.7/lib/libmysql.dll" "C:/mysql_connector/lib/libmysqlclient.dll.a" "C:/mysql_connector/lib/libmysqlclient_r.dll.a" ${Boost_LIBRARY_DIR})
Notice how I have linked the libraries libmysqlclient.dll.a and libmysqlclient_r.dll.a which is what I got from Cygwin.
When I run the app now it successfully gets the driver instance and to the console is outputted
Starting DBConnectionManaged - Updated
Getting driver instance
Got driver instance
But when I try and connect with driver->connect I then get the following error
0 [main] MySQLTest 2976 C:\Users\Chris\.CLion2016.2\system\cmake\generated\MySQLTest-8702ae13\8702ae13\Debug\MySQLTest.exe: *** fatal error - Internal error: TP_NUM_C_BUFS too small: 50
When I put it through the debugger, it fails on the driver->connect with
gdb: unknown target exception 0xe06d7363 at 0x7fff11347788
Program received signal ?, Unknown signal.
0x00007fff11347788 in RaiseException () from /cygdrive/c/WINDOWS/System32/KERNELBASE.dll
Update 2
Everything I've read points the mysql connector binaries should work fine, so I started again. Below is now the contents of my cmake file
cmake_minimum_required(VERSION 3.6)
project(MySQLTest)
#add_compile_options("-v")
SET(GCC_COVERAGE_LINK_FLAGS )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(BOOST_INCLUDE_DIR C:/boost_1_61_0)
set(BOOST_LIBRARY_DIR C:/boost_1_61_0/libs)
include_directories("C:/Program\ Files/MySQL/MySQL\ Connector\ C++\ 1.1.7/include" "C:/Program\ Files/MySQL/MySQL\ Connector\ C++\ 1.1.7/include/cppconn" ${BOOST_INCLUDE_DIR})
set(SOURCE_FILES main.cpp DBConnectionManager.cpp)
add_executable(MySQLTest ${SOURCE_FILES})
find_package(Boost COMPONENTS REQUIRED)
link_directories(C:/Program\ Files/MySQL/MySQL\ Connector\ C++\ 1.1.7/lib/opt)
target_link_libraries(MySQLTest C:/Program\ Files/MySQL/MySQL\ Connector\ C++\ 1.1.7/lib/opt/mysqlcppconn.lib ${Boost_LIBRARY_DIR})
Now when I compile I get the original error
C:/Program Files/MySQL/MySQL Connector C++ 1.1.7/lib/opt/mysqlcppconn.lib(mysqlcppconn.dll.b):(.text+0x2): relocation truncated to fit: R_X86_64_32 against symbol `__imp_get_driver_instance' defined in .idata$5 section in C:/Program Files/MySQL/MySQL Connector C++ 1.1.7/lib/opt/mysqlcppconn.lib(mysqlcppconn.dll.b)
That sounds like to me like my app is compiling as 32 bit instead of 64 bit. As a test I ran the following code:
cout << "Int size is: " << sizeof(int) << endl;
The code above prints 4 (shouldn't it be 8 if it was compiled as 64 bit).
If my thinking is correct, why isn't it compiling it as 64 bit, I've tried setting the compiler flag -m64 but makes no difference. I've installed the Cygwinx64 as well which CLion is using.
You can use MySQL Connector C++
This is how to configure using Cmake
cmake_minimum_required(VERSION 3.7)
project(projectname)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
Include the dirs where you extracted the mysql-connector-cpp - download
include_directories(/usr/local/include/mysql-connector-cpp/include)
Create a cmake variable containing the project source files
set(SOURCE_FILES main.cpp)
Create your executable
add_executable(projectname ${SOURCE_FILES})
Link after creating executable
target_link_libraries(projectname mysqlcppconn)
Your CMakeList should at least have this or look like this in this order
cmake_minimum_required(VERSION 3.7)
project(projectname)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
include_directories(/usr/local/include/mysql-connector-cpp/include)
set(SOURCE_FILES main.cpp)
add_executable(projectname ${SOURCE_FILES})
target_link_libraries(projectname mysqlcppconn)
You can use mysql++ library to connect to mysql from c++.
For that install mysql++,
(Ubuntu)
sudo apt-get install mysql-server mysql-client
sudo apt-get install libmysqlclient-dev libmysql++-dev libmysqlcppconn-dev
(Mac)
brew install mysql++
include library by adding,
/usr/include/mysql++
/usr/include/mysql
and add linkers,
-lmysqlpp -lmysqlclient
Example code,
#include <iostream>
#include <string>
#include <mysql++.h>
#include <mysql.h>
#define dbname "dbname"
#define server "localhost"
#define user "username"
#define pass "password"
using namespace std;
using namespace mysqlpp;
int main() {
Connection con(true);
try {
con.connect(dbname, server, user, pass);
cout << "Connected to database\n";
string s = "SELECT * FROM mirrors_mee WHERE id=1";
Query q = con.query(s);
StoreQueryResult sq = q.store();
StoreQueryResult::iterator it;
it = sq.begin();
while (it != sq.end()) {
Row row = *it;
cout << row[5] << " " << row[6] << " " << row[7] << endl;
it++;
}
} catch (Exception &e) {
cout << e.what() << endl;
}
return 0;
}
You will get full documentation of the library here.