I am trying to use sqlite3 in a ROS node. I think that ROS depends on sqlite3 so I already have the library on my system. The header file is in /usr/lib/. However, when I build my tests with catkin, I get linker errors against the functions in the sqlite3.h header. What do I need to do in my CMake to build against sqlite3?
I included relevant files, but I think the only one you might really need to see is the CMakeLists.txt.
I'm using ros melodic.
Linker errors:
/home/linuxbrew/.linuxbrew/Cellar/cmake/3.15.1/bin/cmake -E cmake_link_script CMakeFiles/sqlite_gtest.dir/link.txt --verbose=1
/usr/bin/c++ -rdynamic CMakeFiles/sqlite_gtest.dir/test/sqlite_test.cpp.o -o /home/alexmussell/catkin_ws/devel/.private/tros_logging/lib/tros_logging/sqlite_gtest -L/home/alexmussell/catkin_ws/build/tros_logging/gtest -Wl,-rpath,/home/alexmussell/catkin_ws/build/tros_logging/gtest:/home/alexmussell/catkin_ws/build/tros_logging/gtest/googlemock/gtest:/opt/ros/melodic/lib:/home/alexmussell/catkin_ws/devel/.private/tros_logging/lib gtest/googlemock/gtest/libgtest.so /opt/ros/melodic/lib/libroscpp.so -lboost_filesystem -lboost_signals /opt/ros/melodic/lib/librosconsole.so /opt/ros/melodic/lib/librosconsole_log4cxx.so /opt/ros/melodic/lib/librosconsole_backend_interface.so -llog4cxx -lboost_regex /opt/ros/melodic/lib/libroscpp_serialization.so /opt/ros/melodic/lib/libxmlrpcpp.so /opt/ros/melodic/lib/librostime.so /opt/ros/melodic/lib/libcpp_common.so /usr/lib/x86_64-linux-gnu/libconsole_bridge.so.0.4 -lboost_system -lboost_thread -lboost_chrono -lboost_date_time -lboost_atomic -lpthread /home/alexmussell/catkin_ws/devel/.private/tros_logging/lib/libtros_logging.so -lpthread
/home/alexmussell/catkin_ws/devel/.private/tros_logging/lib/libtros_logging.so: undefined reference to `sqlite3_step'
/home/alexmussell/catkin_ws/devel/.private/tros_logging/lib/libtros_logging.so: undefined reference to `sqlite3_open'
/home/alexmussell/catkin_ws/devel/.private/tros_logging/lib/libtros_logging.so: undefined reference to `sqlite3_prepare_v2'
/home/alexmussell/catkin_ws/devel/.private/tros_logging/lib/libtros_logging.so: undefined reference to `sqlite3_finalize'
/home/alexmussell/catkin_ws/devel/.private/tros_logging/lib/libtros_logging.so: undefined reference to `sqlite3_bind_text'
/home/alexmussell/catkin_ws/devel/.private/tros_logging/lib/libtros_logging.so: undefined reference to `sqlite3_bind_int64'
/home/alexmussell/catkin_ws/devel/.private/tros_logging/lib/libtros_logging.so: undefined reference to `sqlite3_close'
/home/alexmussell/catkin_ws/devel/.private/tros_logging/lib/libtros_logging.so: undefined reference to `sqlite3_errmsg'
collect2: error: ld returned 1 exit status
CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3)
project(tros_logging)
find_package(catkin REQUIRED COMPONENTS
roscpp
rostest
)
catkin_package(
INCLUDE_DIRS
include
LIBRARIES
${PROJECT_NAME}
CATKIN_DEPENDS
roscpp
)
set(${PROJECT_NAME}_SRCS
src/sqlite_logging_database.cpp
)
include_directories(
include
${catkin_INCLUDE_DIRS}
)
add_library(${PROJECT_NAME} ${${PROJECT_NAME}_SRCS})
#############
## Testing ##
#############
catkin_add_gtest(sqlite_gtest
test/sqlite_test.cpp
)
target_link_libraries(sqlite_gtest
${catkin_LIBRARIES}
${PROJECT_NAME}
)
Where I import the header (sqlite_logging_database.h)
#pragma once
#include "tros_logging/logging_database.h"
#include <sqlite3.h>
namespace tros_logging
{
class SQLiteLoggingDatabase : public LoggingDatabase
{
public:
SQLiteLoggingDatabase(std::string sqlite_database_file);
~SQLiteLoggingDatabase();
bool logEvent(Event event);
bool logError(Error error);
bool logTiming(Timing timing);
bool logMetric(Metric metric);
Event loadEvent(std::string uuid);
Error loadError(std::string uuid);
Timing loadTiming(std::string uuid);
Metric loadMetric(std::string uuid);
private:
sqlite3* db_connection;
void checkError(int error_code);
};
class SQLiteError : public std::runtime_error
{
public:
explicit SQLiteError(std::string what) : std::runtime_error(what)
{
}
};
}
CPP File that implements my code (sqlite_logging_database.cpp)
#include "tros_logging/sqlite_logging_database.h"
#include <ros/ros.h>
namespace tros_logging
{
SQLiteLoggingDatabase::SQLiteLoggingDatabase(std::string sqlite_database_file)
{
int err = 0;
err = sqlite3_open(sqlite_database_file.c_str(), &(this->db_connection));
if(err)
{
ROS_ERROR_STREAM("Error opening sqlite database file: " << sqlite_database_file << " : " << sqlite3_errmsg(this->db_connection));
}
}
SQLiteLoggingDatabase::~SQLiteLoggingDatabase()
{
sqlite3_close(this->db_connection);
}
bool SQLiteLoggingDatabase::logEvent(Event event)
{
sqlite3_stmt * stmt;
std::string sql = "INSERT INTO events (uuid, type, parent_event_uuid, timestamp) VALUES (?, ?, ?, ?)";
try
{
int err = sqlite3_prepare_v2(this->db_connection, sql.c_str(), -1, &stmt, NULL);
this->checkError(err);
err = sqlite3_bind_text(stmt, 1, event.uuid.c_str(), event.uuid.length(), SQLITE_TRANSIENT);
this->checkError(err);
err = sqlite3_bind_text(stmt, 2, event.type.c_str(), event.type.length(), SQLITE_TRANSIENT);
this->checkError(err);
err = sqlite3_bind_text(stmt, 3, event.parent_uuid.c_str(), event.parent_uuid.length(), SQLITE_TRANSIENT);
this->checkError(err);
err = sqlite3_bind_int64(stmt, 4, event.timestamp.toNSec());
this->checkError(err);
err = sqlite3_step(stmt);
this->checkError(err);
err = sqlite3_finalize(stmt);
this->checkError(err);
}
catch(const SQLiteError e)
{
ROS_ERROR_STREAM(e.what() << '\n');
}
}
bool SQLiteLoggingDatabase::logError(Error error)
{
}
bool SQLiteLoggingDatabase::logTiming(Timing timing)
{
}
bool SQLiteLoggingDatabase::logMetric(Metric metric)
{
}
Event SQLiteLoggingDatabase::loadEvent(std::string uuid)
{
}
Error SQLiteLoggingDatabase::loadError(std::string uuid)
{
}
Timing SQLiteLoggingDatabase::loadTiming(std::string uuid)
{
}
Metric SQLiteLoggingDatabase::loadMetric(std::string uuid)
{
}
void SQLiteLoggingDatabase::checkError(int error_code)
{
if(error_code)
{
std::string err_msg = sqlite3_errmsg(this->db_connection);
ROS_ERROR_STREAM("SQLITE ERROR: " << err_msg);
throw SQLiteError(err_msg);
}
}
}
If your library depends on SQLite3, as the error messages and your file naming suggest, you should import this package into CMake using find_package(SQLite3). It doesn't appear (based on the error output) that the SQLite3 library was linked via catkin_LIBRARIES, so you may have to do this manually:
...
# Tell CMake to locate the SQLite3 package on your machine.
find_package(SQLite3 REQUIRED)
add_library(${PROJECT_NAME} ${${PROJECT_NAME}_SRCS})
# Link the SQLite3 imported target to your own library.
target_link_libraries(${PROJECT_NAME} PUBLIC SQLite::SQLite3)
...
Related
This is c++ code to get IP address (main.cpp) (project -> Prueba2 ).
#include <iostream>
#include <windows.h>
#include <wininet.h>
std::string real_ip() {
HINTERNET net = InternetOpen("IP retriever",
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
0);
HINTERNET conn = InternetOpenUrl(net,
"http://myexternalip.com/raw",
NULL,
0,
INTERNET_FLAG_RELOAD,
0);
char buffer[4096];
DWORD read;
InternetReadFile(conn, buffer, sizeof(buffer)/sizeof(buffer[0]), &read);
InternetCloseHandle(net);
return std::string(buffer, read);
}
int main() {
std::cout << real_ip() << std::endl;
return 0;
}
CMakeLists.txt file for compiling.
cmake_minimum_required(VERSION 3.22)
project(Prueba2)
set(CMAKE_CXX_STANDARD 20)
add_executable(Prueba2 main.cpp)
I have to link this library but i don't know how, this error appears. I know how to compile it with g++ adding the library with -lwininet and it works correctly, i'm trying to do it with cmake now. Thank you for your help
undefined reference to `__imp_InternetOpenA'
C:\Program Files\JetBrains\CLion 2022.1.3\bin\mingw\bin/ld.exe: C:/Users/JAVIER/CLionProjects/Prueba2/main.cpp:13: undefined reference to `__imp_InternetOpenUrlA'
C:\Program Files\JetBrains\CLion 2022.1.3\bin\mingw\bin/ld.exe: C:/Users/JAVIER/CLionProjects/Prueba2/main.cpp:23: undefined reference to `__imp_InternetReadFile'
C:\Program Files\JetBrains\CLion 2022.1.3\bin\mingw\bin/ld.exe: C:/Users/JAVIER/CLionProjects/Prueba2/main.cpp:24: undefined reference to `__imp_InternetCloseHandle'
You can use target_link_libraries:
...
add_executable(Prueba2 main.cpp)
target_link_libraries(Prueba2 wininet)
I am trying to create a simple OpenSSL poject in CLion but it can suceed in linking it.
This is my final CMakeLists.txt file (after many tries) which gives less errors:
cmake_minimum_required(VERSION 3.16)
project(duplicates_finder)
set(CMAKE_CXX_STANDARD 17)
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -L . -lssl -lcrypto")
set(SOURCE_FILES main.cpp)
add_executable(${PROJECT_NAME} ${SOURCE_FILES})
find_package(OpenSSL REQUIRED)
if (OPENSSL_FOUND)
# Add the include directories for compiling
target_include_directories(${PROJECT_NAME} PUBLIC ${OPENSSL_INCLUDE_DIR})
# Add the static lib for linking
target_link_libraries(${PROJECT_NAME} OpenSSL::SSL OpenSSL::Crypto)
message(STATUS "Found OpenSSL ${OPENSSL_VERSION}")
else()
message(STATUS "OpenSSL Not Found")
endif()
include_directories(C:\\OpenSSL-Win32\\include)
link_directories(C:\\OpenSSL-Win32\\lib\\MinGW)
This is the file I am trying to compile:
#include <string>
#include <iostream>
#include <filesystem>
#include <string>
#include <openssl/sha.h>
#include "openssl/ssl.h"
#include <sstream>
#include <iomanip>
using namespace std;
namespace fs = std::filesystem;
//string sha256(const string& str)
//{
// unsigned char hash[SHA256_DIGEST_LENGTH];
// SHA256_CTX sha256;
// SHA256_Init(&sha256);
// SHA256_Update(&sha256, str.c_str(), str.size());
// SHA256_Final(hash, &sha256);
// stringstream ss;
// for(unsigned char i : hash)
// {
// ss << hex << setw(2) << setfill('0') << (int)i;
// }
// return ss.str();
//}
int main() {
std::cout << "SSLeay Version: " << SSLeay_version(SSLEAY_VERSION) << std::endl;
SSL_library_init();
auto ctx = SSL_CTX_new(SSLv23_client_method());
if (ctx) {
auto ssl = SSL_new(ctx);
if (ssl) {
std::cout << "SSL Version: " << SSL_get_version(ssl) << std::endl;
SSL_free(ssl);
} else {
std::cout << "SSL_new failed..." << std::endl;
}
SSL_CTX_free(ctx);
} else {
std::cout << "SSL_CTX_new failed..." << std::endl;
}
}
And these are the errors:
====================[ Build | all | Debug ]=====================================
"C:\Program Files\JetBrains\CLion 2020.1\bin\cmake\win\bin\cmake.exe" --build C:\Users\USERNAME\CLionProjects\duplicates_finder\cmake-build-debug --target all -- -j 8
[ 50%] Linking CXX executable duplicates_finder.exe
C:/PROGRA~2/EMBARC~1/Dev-Cpp/TDM-GC~1/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: CMakeFiles\duplicates_finder.dir/objects.a(main.cpp.obj): in function `main':
C:/Users/USERNAME/CLionProjects/duplicates_finder/main.cpp:42: undefined reference to `SSLeay_version'
C:/PROGRA~2/EMBARC~1/Dev-Cpp/TDM-GC~1/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:/Users/USERNAME/CLionProjects/duplicates_finder/main.cpp:43: undefined reference to `SSL_library_init'
C:/PROGRA~2/EMBARC~1/Dev-Cpp/TDM-GC~1/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:/Users/USERNAME/CLionProjects/duplicates_finder/main.cpp:44: undefined reference to `SSLv23_client_method'
C:/PROGRA~2/EMBARC~1/Dev-Cpp/TDM-GC~1/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:/Users/USERNAME/CLionProjects/duplicates_finder/main.cpp:44: undefined reference to `SSL_CTX_new'
C:/PROGRA~2/EMBARC~1/Dev-Cpp/TDM-GC~1/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:/Users/USERNAME/CLionProjects/duplicates_finder/main.cpp:46: undefined reference to `SSL_new'
C:/PROGRA~2/EMBARC~1/Dev-Cpp/TDM-GC~1/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:/Users/USERNAME/CLionProjects/duplicates_finder/main.cpp:48: undefined reference to `SSL_get_version'
C:/PROGRA~2/EMBARC~1/Dev-Cpp/TDM-GC~1/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:/Users/USERNAME/CLionProjects/duplicates_finder/main.cpp:49: undefined reference to `SSL_free'
C:/PROGRA~2/EMBARC~1/Dev-Cpp/TDM-GC~1/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:/Users/USERNAME/CLionProjects/duplicates_finder/main.cpp:53: undefined reference to `SSL_CTX_free'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [duplicates_finder.exe] Error 1
CMakeFiles\duplicates_finder.dir\build.make:87: recipe for target 'duplicates_finder.exe' failed
mingw32-make.exe[1]: *** [CMakeFiles/duplicates_finder.dir/all] Error 2
mingw32-make.exe: *** [all] Error 2
CMakeFiles\Makefile2:74: recipe for target 'CMakeFiles/duplicates_finder.dir/all' failed
Makefile:82: recipe for target 'all' failed
I restared my PC.
I also added the line:
target_link_libraries(${PROJECT_NAME} libeay32.lib) //also .a file the result is the same.
And it throws the error that it can't find that file.
Also added the files: libeay32.a, libeay32.def, libeay32.lib and ssleay32.a, ssleay32.def, ssleay32.lib to the project folder and also to the cmak-build-debug folder. => Still not working.
Also renamed libeay32.a to libeay32.dll.a and ssleay32.a to ssleay32.dll.a as on the another topic from stackoverflow says but it is still not working too.
No matter I do it is not compiling at all.
I spent all day searching for a solution but in vain.
I am using Windows 7 x64 and OpenSSL 1.1.1m 14 Dec 2021.
Thank you in advance!
I am learning to use cmake and I am trying to compile a simple set of tests using gtest for a very small project that I wrote.
my CMakeLists.txt looks like
cmake_minimum_required(VERSION 2.6)
project(circuit_sim)
include(FetchContent)
FetchContent_Declare(
googletest
# Specify the commit you depend on and update it regularly.
URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
)
# For Windows: Prevent overriding the parent project's compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
add_executable(test Connector.cpp test.cpp)
target_link_libraries(test gtest_main)
I got most of it from the googletest docs. I am trying to compile an executable that has a main() in test.cpp and relies on a Connector class in Connector.cpp and Connector.h. All files are in the same directory
when I run cmake . and then make I get the following error:
/usr/bin/ld: CMakeFiles/test.dir/test.cpp.o: in function `AllTests_CircuitTest_Test::TestBody()':
test.cpp:(.text+0x33): undefined reference to `Connector::Connector()'
/usr/bin/ld: test.cpp:(.text+0x4c): undefined reference to `Connector::Connector()'
/usr/bin/ld: test.cpp:(.text+0x6d): undefined reference to `Connector::Connector(Connector*)'
/usr/bin/ld: test.cpp:(.text+0x7d): undefined reference to `Connector::connect(Connector*)'
/usr/bin/ld: test.cpp:(.text+0x93): undefined reference to `Connector::in(unsigned long, unsigned long)'
/usr/bin/ld: test.cpp:(.text+0xb8): undefined reference to `Connector::out()'
/usr/bin/ld: test.cpp:(.text+0xc4): undefined reference to `Connector::get_out_conn()'
/usr/bin/ld: test.cpp:(.text+0xd6): undefined reference to `Connector::get_v()'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/test.dir/build.make:86: test] Error 1
make[1]: *** [CMakeFiles/Makefile2:139: CMakeFiles/test.dir/all] Error 2
make: *** [Makefile:130: all] Error 2
It seems that cmake did not know to include Connector.cpp in the compilation even though I specified it in the CMakeLists.txt. What am I doing wrong?
Code for Connector.cpp, currently it doesn't do very much lol but it's a wip
#include "Connector.h"
#include "circuit_utils.h"
Connector::Connector(){
this->v = 0;
this->c = 0;
this->out_conn = nullptr;
}
Connector::Connector(Connector* out_conn){
this->v = 0;
this->c = 0;
this->out_conn = out_conn;
}
Connector* Connector::connect(Connector* out_conn){
this->out_conn = out_conn;
return this;
}
Connector* Connector::in(uint64_t v, uint64_t c){
this->v = v;
this->c = c;
//this->out();
return this;
}
Connector* Connector::out(){
if(out_conn != nullptr)
out_conn->in(v, c);
return this;
}
uint64_t Connector::get_v() { return v; }
uint64_t Connector::get_c() { return c; }
Connector* Connector::get_out_conn() { return out_conn; }
std::string Connector::to_string() {
std::string to_return = "";
to_return += "-------------\n";
to_return += "voltage: " + std::to_string(FROM_MICROS(((double)v))) + " volts\n";
to_return += "current: " + std::to_string(FROM_MICROS(((double)c))) + " amps\n";
to_return += "-------------\n";
return to_return;
}
Code for test.cpp
#include <iostream>
#include <unistd.h>
#include "gtest/gtest.h"
#include "Connector.h"
#include "circuit_utils.h"
using namespace std;
TEST (AllTests, CircuitTest) {
Connector* power = new Connector();
Connector* ground = new Connector();
power->connect(new Connector(ground));
power->in(TO_MICROS(3.3), TO_MICROS(3.3));
Connector *cur_conn = power;
while(cur_conn != nullptr){
sleep(5);
cur_conn->out();
cur_conn = cur_conn->get_out_conn();
}
ASSERT_EQ(3.3, ground->get_v());
}
Since you need external class, you should put that class "library" in target_link_libraries(), so that the last line of your CMakeLists.txt will become
target_link_libraries(test connector gtest_main)
Also, in another CMakeLists.txt which is in the same directory as Connector.cpp, your should declare them as one library:
set(SOURCES Connector.cpp)
add_library(connector STATIC ${SOURCES})
I'm trying to create go app, which uses some C++ code from sdk in shared library.
Added reference to target library with #cgo LDFLAGS:
#cgo LDFLAGS: -L/opt/cprocsp/lib/amd64 -lxades -v
and build go app with
go build -o main .
Compilation goes ok, but linking fails with error
/usr/bin/ld: $WORK/b001/_x003.o: undefined reference to symbol 'CryptReleaseContext'
/usr/bin/ld: //opt/cprocsp/lib/amd64/libcapi10.so.4: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
Function CryptReleaseContext exists in /opt/cprocsp/lib/amd64/libxades.so.
With -v option I noticed linker arguments order
/usr/lib/gcc/x86_64-linux-gnu/8/collect2 ... $WORK/b001/_cgo_main.o $WORK/b001/_x001.o $WORK/b001/_x002.o $WORK/b001/_x003.o -lxades -lstdc++ ...
With Google I found that arguments order may be important, but I can't find a way to control them and stucking with it. How can I build app?
Example:
main.go
package main
import "log"
func main() {
data := "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<Envelope xmlns=\"urn:envelope\">" +
"<Data>Hello, World!</Data>" +
"<Node xml:id=\"nodeID\">Hello, Node!</Node>" +
"</Envelope>"
signed := Sign(data)
log.Print(signed)
}
signer.go
package main
/*
#cgo LDFLAGS: -L/opt/cprocsp/lib/amd64 -lxades -v
#include <stdarg.h>
#include <stdlib.h>
#include "signer.h"
*/
import "C"
import "log"
import "unsafe"
func Sign(data string) (result string) {
log.Print("Signing message")
c_data := C.CString(data)
defer C.free(unsafe.Pointer(c_data))
c_result := C.CString(result)
defer C.free(unsafe.Pointer(c_result))
C.sign(c_data, c_result)
return C.GoString(c_result)
}
signer.h
void sign(char* src, char *dst);
signer.cpp
SDK's example code, that uses functions from /opt/cprocsp/lib/amd64/libxades.so
...
extern "C" {
void sign(char* src, char *dst){
BYTE *pbToBeSigned = (BYTE *) src;
DWORD cbToBeSigned = strlen(src);
static XADES_SIGN_MESSAGE_PARA signParams = { sizeof(signParams) };
initSignParams(&signParams);
PCRYPT_DATA_BLOB pSignedMessage = 0;
// Создаем подписанное сообщение
if (!XadesSign(&signParams, NULL, FALSE, pbToBeSigned, cbToBeSigned, &pSignedMessage)) {
cout << "XadesSign() failed" << endl;
return;
}
vector<unsigned char> message(pSignedMessage->cbData);
copy(pSignedMessage->pbData, pSignedMessage->pbData + pSignedMessage->cbData, message.begin());
char* result = reinterpret_cast<char*>(message.data());
strcpy(dst, result);
}
}
Update
#cgo LDFLAGS: -L/opt/cprocsp/lib/amd64 -Wl,-rpath,/opt/cprocsp/lib/amd64 -lxades -v
didn't help
answer was in second error:
#cgo LDFLAGS: -L/opt/cprocsp/lib/amd64 -lxades -lcapi10 -lcapi20 -v
first time when I'm trying to add lcapi10 - missed that new error tells about lcapi20, not 10
Hello,
I'm trying to use SDL2 in my C++ project under Linkux but have undefined references to core functions. I included the header files and set up the CmakeLists correctly (I think), so I don't understand why he does not find the functions.
My C++ code:
#include "SDL.h"
#include "SDL_mixer.h"
#include "SDL_image.h"
#include <iostream>
using namespace std;
#define NUM_WAVEFORMS 2
const char* _waveFileNames[] = {"Kick-Drum-1.wav", "Snare-Drum-1.wav"};
Mix_Chunk* _sample[2];
// Initializes the application data
int Init(void) {
memset(_sample, 0, sizeof(Mix_Chunk*) * 2);
// Set up the audio stream
int result = Mix_OpenAudio(44100, AUDIO_S16SYS, 2, 512);
if( result < 0 ) {
fprintf(stderr, "Unable to open audio: %s\n", SDL_GetError());
exit(-1);
}
result = Mix_AllocateChannels(4);
if( result < 0 ) {
fprintf(stderr, "Unable to allocate mixing channels: %s\n", SDL_GetError());
exit(-1);
}
// Load waveforms
for( int i = 0; i < NUM_WAVEFORMS; i++ ) {
_sample[i] = Mix_LoadWAV(_waveFileNames[i]);
if( _sample[i] == NULL ) {
fprintf(stderr, "Unable to load wave file: %s\n", _waveFileNames[i]);
}
}
return true;
}
int main() {
bool retval = Init();
cout << retval << endl;
return 0;
}
My errors:
CMakeFiles/SDL_Test.dir/src/SDL_Test.cpp.o: In function `Init()':
/home/tamas/SDL_Test/src/SDL_Test.cpp:20: undefined reference to `Mix_OpenAudio'
/home/tamas/SDL_Test/src/SDL_Test.cpp:26: undefined reference to `Mix_AllocateChannels'
/home/tamas/SDL_Test/src/SDL_Test.cpp:34: undefined reference to `Mix_LoadWAV_RW'
My CMakeLists.txt:
cmake_minimum_required (VERSION 3.5)
project (SDL_Test)
set (CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_STANDARD_REQUIRED TRUE)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Werror -std=c++11")
set (source_dir "${PROJECT_SOURCE_DIR}/src/")
file (GLOB source_files "${source_dir}/*.cpp")
find_package(SDL2 REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS})
add_executable (SDL_Test ${source_files})
target_link_libraries(SDL_Test ${SDL2_LIBRARIES})
Thanks for the help in advance!
SDL_Mixer comes with a pkg-config file, so you can use CMake's pkg-config support:
include(FindPkgConfig)
pkg_check_modules(SDL2_Mixer REQUIRED IMPORTED_TARGET SDL2_mixer)
target_link_libraries(SDL_Test PkgConfig::SDL2_Mixer)
The IMPORTED TARGET PkgConfig::SDL2_Mixer will be preconfigured with the correct include and linker paths.