defining shared_ptr causes segfault (CMake)

2019-09-14 04:36发布

问题:

While setting up a new project (using CMake, compiler is gcc version 5.2.1, ubuntu (15.10)), I wanted to use a shared_ptr.

This simple main.cpp works fine:

#include <iostream>
#include <memory>    
using namespace std;

int main()
{    
    cout<<"Hi there!"<<endl;
    return 0;
}

But just defining a shared_ptr will cause the program to crash with segfault before even writing "Hi there!".

#include <iostream>
#include <memory>    
using namespace std;

int main()
{    
    cout<<"Hi there!"<<endl;
    shared_ptr<double> test;  // <- new line
    return 0;
}

I added

set(CMAKE_CXX_FLAGS "-std=c++11")

to the CMakeLists.txt. Is there something I'm missing here. I could not find any answers that explain the segfault just because of the definition of a shared_ptr.

The GDB output is not helpful at all:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()

EDIT: Compiling by hand using

g++ -std=c++11 -o testx main.cpp

produces a runable executable for both cases so it has to be a CMake issue i guess. So here is the CMake file for the project:

project(yorld3)
cmake_minimum_required(VERSION 2.8)

set(CMAKE_CXX_FLAGS "-std=c++11")

find_package(OpenGL REQUIRED)
include_directories(${OpenGL_INCLUDE_DIRS})
set(LIBS ${LIBS} ${OpenGL_LIBRARIES})

find_package(GLUT REQUIRED)
include_directories(${GLUT_INCLUDE_DIRS})
set(LIBS ${LIBS} ${GLUT_LIBRARIES})

find_package(Bullet REQUIRED)
include_directories(${Bullet_INCLUDE_DIRS})
set(LIBS ${LIBS} ${Bullet_LIBRARIES})

link_directories(${SRC_BINARY_DIR}/src)

add_subdirectory(src)
INCLUDE_DIRECTORIES(src)
INCLUDE_DIRECTORIES(src/core)
add_executable(test main.cpp )
target_link_libraries(test mycorelib GLU GL glut)

EDIT2: After a lot of testing I manually compiled the program again not linking my lib:

g++ -std=c++11 -g -Wall -I src/core/app -o testx main.cpp src/core/app/yorld_window.cpp -lGL -lGLU -lglut

That way I can reproduce the segfault without using CMake.

回答1:

After a lot more code digging I found out the problem was not related to CMake. A comment to an other question was the solution!

Turns out you have to link to pthread

-lpthread

or just

target_link_libraries(test ... pthread)

That way shared pointers work with glut. I still find it strange that this is in no way detected by the linker!