如何将boost库的目录传递给CMakeLists.txt文件进行编译?



我是CMake和Qt世界的新手。

我想创建一个小的Qt应用程序,可以计算任何数字的阶乘。为了在c++中做到这一点,我使用boost库。

通常,当我用boost编写c++代码时,我会这样编译-

g++ MyCode.cpp -I "C:boost" -o MyCode.exe

现在我试图在Qt中做同样的事情。这里是CMakeLists.txt的代码:-

cmake_minimum_required(VERSION 3.14)
project(FirstProject-ConsoleApplication LANGUAGES CXX)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME ON)
# find_package(Boost 1.76.0 COMPONENTS ...)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(progname file1.cxx file2.cxx)
target_link_libraries(progname ${Boost_LIBRARIES})
endif()
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core)
add_executable(FirstProject-ConsoleApplication
main.cpp
)
target_link_libraries(FirstProject-ConsoleApplication Qt${QT_VERSION_MAJOR}::Core)
install(TARGETS FirstProject-ConsoleApplication
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})

这是main.cpp文件的代码[这是一个控制台应用程序]:-

#include <QCoreApplication>
#include <QDebug>
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>  // 'boost/multiprecision/cpp_int.hpp' file not found
using namespace std;
using boost::multiprecision::cpp_int;  // Use of undeclared identifier 'boost'

cpp_int Factorial(int number) // Unknown type name 'cpp_int'
{
cpp_int num = 1;
for (int i = 1; i <= number; i++)
num = num * i;
return num;
}

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::cout << Factorial(50) << "n";
qInfo() << Factorial(100) << "n";
return a.exec();
}

我想知道,我如何将我的boost文件夹的目录传递给这个CMakeLists.txt文件,以便程序顺利构建?

正如本评论所建议的,在变量CMAKE_PREFIX_PATH中添加安装Boost的路径应该足够了。那么find_package应该能够找到Boost。

或者,根据FindBoost的文档,您还可以通过设置变量BOOST_ROOT来提示Boost的位置。例如,假设您从CMakeList.txt所在的路径运行cmake,您可以运行

cmake -DBOOST_ROOT=/path/to/boost .

(最后的"; "表示CMakeList.txt将在当前目录中找到)

或者,您可以使用变量BOOST_LIBRARYDIRBOOST_INCLUDEDIR指示库和头文件的位置

cmake -DBOOST_INCLUDEDIR=/path/to/boost/include -DBOOST_LIBRARYDIR=/path/to/boost/lib .

您可以直接在CMakeList.txt文件中设置这些变量,而不是在命令行中给出这个变量,在find_package

之前添加
SET(BOOST_ROOT "/path/to/boost/")

SET(BOOST_INCLUDEDIR "/path/to/boost/include")
SET(BOOST_LIBRARYDIR "/path/to/boost/lib")

附注:

  • #include <bits/stdc++.h>应避免使用
  • using namespace std被认为是不良做法。

最新更新