首页 > 解决方案 > 使用 cmake 构建带有 -I、-L 和 -l 的 g++ 命令

问题描述

这是我要运行的程序,main.cpp:

#include <iostream>
#include "yaracpp/yaracpp.h"

int main() {
    yaracpp::YaraDetector yara;
    yara.addRules(R"(

        rule example {
            strings:
                $s = "Hello"
            condition:
                $s
        })");


    if (yara.analyze("test_file")) {
        for (const auto& rule : yara.getDetectedRules()) {
            std::cout << rule << '\n';
        }
    }
}

当我在终端上运行此命令时,它会成功编译:

g++ -Iinclude -Ibuild/deps/yara/src/yara/libyara/include/ -Lbuild/src/ -Lbuild/deps/yara/src/yara/libyara/.libs/ main.cpp -lyaracpp -lyara -lpthread -lssl -lcrypto

我的 CMakeLists.txt 是:

cmake_minimum_required(VERSION 3.6)
project(main CXX C)

add_executable(main main.cpp)

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Iinclude -Ibuild/deps/yara/src/yara/libyara/include -Lbuild/src -Lbuild/deps/yara/src/yara/libyara/.libs/")


target_link_libraries (main yaracpp yara pthread ssl crypto)

当我尝试构建它时会发生这种情况:

制作。

-- The CXX compiler identification is GNU 7.4.0
-- The C compiler identification is GNU 7.4.0
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/mevasu/yaracpp

制作

[ 50%] Building CXX object CMakeFiles/main.dir/main.cpp.o
/home/mevasu/yaracpp/main.cpp:2:10: fatal error: yaracpp/yaracpp.h: No such file or directory
 #include "yaracpp/yaracpp.h"
          ^~~~~~~~~~~~~~~~~~~
compilation terminated.
CMakeFiles/main.dir/build.make:62: recipe for target 'CMakeFiles/main.dir/main.cpp.o' failed
make[2]: *** [CMakeFiles/main.dir/main.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/main.dir/all' failed
make[1]: *** [CMakeFiles/main.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

标签: buildcmakeg++

解决方案


Looking at the output, there is the following line:

c++: error: yaracpp/main.cpp: No such file or directory

Does the file exist? Looking at your CMakeLists.txt, the file appears in the following command:

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} [..] yaracpp/main.cpp ")
                                              ^^^^^^^^^^^^^^^^

Why do you add yaracpp/main.cpp into CMAKE_CXX_FLAGS when it (apparently) has already been added in the following line?

add_executable(main main.cpp)
                    ^^^^^^^^

I highly suggest learning the basics of CMake before continuing in your endeavors.


推荐阅读