Undefined references when using SDL2 with Cmake/Linux/C++ - c++

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.

Related

Unable to create an OpenSSL project with CLion

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!

Why won't music play using SDL

#include<iostream>
#include <SDL_mixer.h>
#include <SDL.h>
using namespace std;
int main(int argc, char* argv[])
{
SDL_Init(SDL_INIT_AUDIO);
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
{
cout << "Error: " << Mix_GetError() << std::endl;
}
Mix_Music* song = Mix_LoadMUS("sample.wav");
Mix_PlayMusic(song, 1);
Mix_FreeMusic(song);
song = nullptr;
Mix_Quit();
SDL_Quit();
return 0;
}
I am trying to play a simple song, that I converted to WAV. It is located within the program's folder. I didn't get any errors/warnings when compling and the libraries seem to be linked correctly. On failure, loadMUS returns NULL (which isn't the case) and PlayMusic returns -1 upon failure (which again isn't the case). Yet, when I run the program nothing is heard. This is my first time working with SDL.
To just play a wave file this sample will work with SDL2:
#include <SDL.h>
#include <SDL_audio.h>
int main() {
SDL_Init(SDL_INIT_AUDIO);
SDL_AudioSpec spec{};
Uint8 *audio_buf{};
Uint32 audio_len{};
SDL_LoadWAV("path_to.wav", &spec, &audio_buf, &audio_len);
SDL_AudioSpec ob_spec{};
auto device = SDL_OpenAudioDevice(NULL, 0, &spec, &ob_spec, SDL_AUDIO_ALLOW_ANY_CHANGE);
SDL_QueueAudio(device, audio_buf, audio_len);
SDL_PauseAudioDevice(device, 0);
SDL_Delay(5000);
SDL_CloseAudioDevice(device);
SDL_FreeWAV(audio_buf);
SDL_QuitSubSystem(SDL_INIT_AUDIO);
}
BTW to link easy to SDL2 just use CMake with
cmake_minimum_required(VERSION 3.19)
project(sample_sdl VERSION 1.0)
find_package(SDL2 REQUIRED)
add_executable(${PROJECT_NAME} src/main.cpp)
set_property(TARGET ${PROJECT_NAME} PROPERTY LINKER_LANGUAGE CXX)
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20)
target_link_libraries(${PROJECT_NAME} PRIVATE SDL2::SDL2 SDL2::SDL2main)

How to build a ros node that uses sqlite3?

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)
...

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

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.

Clion (cmake) won't link the libraries [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm having a problem when trying to link SDL2 and GL libraries to Clion (cmake). Despite changing the cmakelists.txt and adding the target-link-libraries() function. So the cmake file looked like this:
cmake_minimum_required(VERSION 3.9)
project(OpenGL1)
set(CMAKE_CXX_STANDARD 17)
target_link_libraries(OpenGL1 SDL2 GL)
add_executable(OpenGL1 main.cpp Display1.cpp Display1.h)
But with no luck. Clion would not link the libraries with errors such as undifined refference to functions of the libraries.
Then a friend suggested it that I would wite that into cmakelists file:
cmake_minimum_required(VERSION 3.9)
project(OpenGL1)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -lGL -lSDL2 -lOpenGL")
add_executable(OpenGL1 main.cpp Display1.cpp Display1.h)
And it kinda worked... But it would not find the -lOpenGL.
Last but not least, my project will not compile with the traditional way in the terminal with g++. And it will compile fine with one .cpp file.
My project consists of 2 cpp files and a header file. Like that:
main.cpp
Display1.cpp
Display.h
And code of the files is the following:
main.cpp
#include <iostream>
#include "Display.h"
using namespace std;
int main() {
Display d1(800,600,"Hello");
while (!d1.m_isClosed()){
d1.Clear(0.0f, 0.15f, 0.3f, 1.0f);
d1.Update();
}
return 0;
}
Display1.cpp
#include "Display.h"
#include <GL/glew.h>
using namespace std;
Display::Display(int width, int height, const string title) {
SDL_Init(SDL_INIT_EVERYTHING);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE,8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE,8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE,8);
SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE,32);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);
m_window = SDL_CreateWindow(title.c_str(),SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,width,height,SDL_WINDOW_OPENGL);
m_glContext = SDL_GL_CreateContext(m_window);
GLenum status = glewInit();
if (status != GLEW_OK)
cerr << "Glew failed!" << endl;
isClosed = false;
}
Display::~Display() {
SDL_GL_DeleteContext(m_glContext);
SDL_DestroyWindow(m_window);
SDL_Quit();
}
void Display::Clear(float r, float g, float b, float a) {
glClearColor(r,g,b,a);
glClear(GL_COLOR_BUFFER_BIT);
}
bool Display::m_isClosed() {
return isClosed;
}
void Display::Update() {
SDL_GL_SwapWindow(m_window);
SDL_Event e;
while (SDL_PollEvent(&e)){
if (e.type == SDL_QUIT)
isClosed = true;
}
}
Display1.h
#ifndef OPENGL_DISPLAY_H
#define OPENGL_DISPLAY_H
#include <iostream>
#include <SDL2/SDL.h>
using namespace std;
class Display {
SDL_Window* m_window;
SDL_GLContext m_glContext;
bool isClosed;
public:
Display(int width, int height, string title);
virtual ~Display();
void Update();
bool m_isClosed();
void Clear(float r, float g, float b, float a);
};
#endif //OPENGL_DISPLAY_H
Now, i know that others have asked the same, but nothing could help me so that's why I'm asking. I'm running Ubuntu 17.10 (64-bit). Thanks in advance!
You have to fix your CMakeLists.txt:
cmake_minimum_required(VERSION 3.9)
project(OpenGL1)
set(CMAKE_CXX_STANDARD 17)
find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)
set(SDL2_INCLUDE_DIRS /usr/include/SDL2)
set(SDL2_LIBRARIES /usr/lib/x86_64-linux-gnu/libSDL2.so)
include_directories(${OPENGL_INCLUDE_DIRS} ${GLEW_INCLUDE_DIRS} ${SDL2_INCLUDE_DIRS})
add_executable(OpenGL1 main.cpp Display1.cpp Display1.h)
target_link_libraries(OpenGL1 ${OPENGL_LIBRARIES} ${GLEW_LIBRARIES} ${SDL2_LIBRARIES})
First find the OpenGL files with find_package(OpenGL REQUIRED). Then set the paths for SDL2. Set the include directories for your target (OpenGL1). Add your target. Link libraries to your target.
A better way to use SDL2 is to use FindSDL2.cmake and add find_package(SDL2) to your CMakeLists.txt:
cmake_minimum_required(VERSION 3.9)
project(OpenGL1)
set(CMAKE_CXX_STANDARD 17)
find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)
find_package(SDL2 REQUIRED)
include_directories(${OPENGL_INCLUDE_DIRS} ${GLEW_INCLUDE_DIRS} ${SDL2_INCLUDE_DIRS})
add_executable(OpenGL1 main.cpp Display1.cpp Display1.h)
target_link_libraries(OpenGL1 ${OPENGL_LIBRARIES} ${GLEW_LIBRARIES} ${SDL2_LIBRARIES})
SDL2 installs its own cmake configuration file called sdl2-config.cmake, so you don't need to download it from github.