使用glew和glfw的opengl的cmake标志

cmake flags for opengl using glew and glfw

我有这个简单的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <stdlib.h>

#include <GL/glew.h>
#include <GL/glfw.h>

int main(int argc, char const* argv[] )
{
    if( !glfwInit() ){
        fprintf( stderr,"failed\
"
);
    }

    return 0;
}

并在我的CmakeLists.txt中:

1
2
3
4
5
6
7
8
9
10
11
PROJECT(test C)
find_package(OpenGL)
ADD_DEFINITIONS(
    -std=c99
    -lGL
    -lGLU
    -lGLEW
    -lglfw
)
SET(SRC test)
ADD_EXECUTABLE(test ${SRC})

运行" cmake"。 不会产生任何错误,但是运行make will会说:

1
2
3
test.c:(.text+0x10): undefined reference to `glfwInit'
collect2: ld returned 1 exit status
make[2]: *** [tut1] Error 1

在跑步的时候:

1
gcc -o test test.c -std=c99 -lGL -lGLU -lGLEW -lglfw

成功编译代码,没有错误。 我如何使cmake与我的代码一起运行?

此外,如果我将这些行添加到主要功能:

1
2
3
4
glfwOpenWindowHint( GLFW_FSAA_SAMPLES, 4 );
glfwOpenWindowHint( GLFW_OPENGL_VERSION_MAJOR, 3 );
glfwOpenWindowHint( GLFW_OPENGL_VERSION_MINOR, 1 );
glfwOpenWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );

即使使用相同的标志运行gcc也会产生错误:

1
2
3
4
5
6
7
test.c: In function ‘main’:
test.c:14: error: ‘GLFW_OPENGL_VERSION_MAJOR’ undeclared (first use in this function)
test.c:14: error: (Each undeclared identifier is reported only once
test.c:14: error: for each function it appears in.)
test.c:15: error: ‘GLFW_OPENGL_VERSION_MINOR’ undeclared (first use in this function)
test.c:16: error: ‘GLFW_OPENGL_PROFILE’ undeclared (first use in this function)
test.c:16: error: ‘GLFW_OPENGL_CORE_PROFILE’ undeclared (first use in this function)

我正在基于kubuntu 10.04,cmake v2.8,libglfw-dev,libglfw2,libglew1.5,libglew1.5-dev和glew-utils的Linux Mint运行。

我是cmake,ggle和glfw的新手。 感谢您的帮助!

干杯!

P


您可以在此处看到一个示例,如何将glake与cmake一起使用。
http://code.google.com/p/assembly3d/source/browse/tools/viewer/CMakeLists.txt

我使用FindGLFW.cmake查找glfw
http://code.google.com/p/assembly3d/source/browse/tools/viewer/cmake_modules/FindGLFW.cmake

另外,ubuntu中的glfw版本是2.6。
GLFW_OPENGL_VERSION_MINOR和GLFW_OPENGL_VERSION_MAJOR仅可用于glfw 2.7,而我认为OpenGL 3.x仅可用于glfw 2.7。

最好


要查看CMake生成的makefile正在执行的命令,请运行make as:

1
make VERBOSE=1

在调试CMake项目时,查看命令非常有帮助。对于提供的示例,将执行以下命令:

1
2
/usr/bin/gcc -std=c99 -lGL -lGLU -lGLEW -lglfw -o CMakeFiles/test.dir/test.c.o -c test.c
/usr/bin/gcc CMakeFiles/test.dir/test.o -o test -rdynamic

CMake生成的makefile会将每个源文件分别编译为一个目标文件(这是gcc -c所做的),然后使用单独的命令将所有目标文件链接在一起。在提供的示例中,在编译阶段而不是在链接阶段指定了OpenGL相关库。不应使用add_definitions指定库,而应使用target_link_libraries命令。

这样的CMakeLists.txt文件应该可以工作:

1
2
3
4
5
6
cmake_minimum_required(VERSION 2.8)
project(test C)
add_definitions(-std=c99)
set(SRC test.c)
add_executable(test ${SRC})
target_link_libraries(test GL GLU GLEW glfw)

不需要为库指定-l前缀,因为target_link_libraries将为UNIX / Linux环境自动添加-l前缀,为Windows环境自动添加.lib扩展。有关target_link_libraries的更多信息,请参见http://www.cmake.org/cmake/help/cmake-2-8-docs.html#command:target_link_libraries


皮克斯公司做到了。以下是其源代码,您可以参考它:
https://github.com/PixarAnimationStudios/OpenSubdiv/blob/master/cmake/FindGLFW.cmake