15.3 检测所需的链接和依赖关系

现在已经生成了所有文件,让我们重新构建。我们应该能够配置和编译源代码,不过不能链接:

  1. $ mkdir -p build
  2. $ cd build
  3. $ cmake ..
  4. $ cmake --build .
  5. ...
  6. Scanning dependencies of target vim
  7. [ 98%] Building C object src/CMakeFiles/vim.dir/main.c.o
  8. [100%] Linking C executable ../bin/vim
  9. ../lib64/libbasic_sources.a(term.c.o): In function `set_shellsize.part.12':
  10. term.c:(.text+0x2bd): undefined reference to `tputs'
  11. ../lib64/libbasic_sources.a(term.c.o): In function `getlinecol':
  12. term.c:(.text+0x902): undefined reference to `tgetent'
  13. term.c:(.text+0x915): undefined reference to `tgetent'
  14. term.c:(.text+0x935): undefined reference to `tgetnum'
  15. term.c:(.text+0x948): undefined reference to `tgetnum'
  16. ... many other undefined references ...

同样,可以从Autotools编译中获取日志文件,特别是链接行,通过在src/CMakeLists.txt中添加以下代码来解决缺少的依赖关系:

  1. # find X11 and link to it
  2. find_package(X11 REQUIRED)
  3. if(X11_FOUND)
  4. target_link_libraries(vim
  5. PUBLIC
  6. ${X11_LIBRARIES}
  7. )
  8. endif()
  9. # a couple of more system libraries that the code requires
  10. foreach(_library IN ITEMS Xt SM m tinfo acl gpm dl)
  11. find_library(_${_library}_found ${_library} REQUIRED)
  12. if(_${_library}_found)
  13. target_link_libraries(vim
  14. PUBLIC
  15. ${_library}
  16. )
  17. endif()
  18. endforeach()

我们可以添加一个库的依赖目标,并且不需要构建,以及不需要将库目标放在一个列表变量中,否则将破坏CMake代码的自变量,特别是对于较大的项目而言。

修改之后,编译和链接:

  1. $ cmake --build .
  2. ...
  3. Scanning dependencies of target vim
  4. [ 98%] Building C object src/CMakeFiles/vim.dir/main.c.o
  5. [100%] Linking C executable ../bin/vim
  6. [100%] Built target vim

现在,我们可以执行编译后的二进制文件,我们新编译的Vim就可使用了!