Below is a small working example of how to link OR-Tools to a CMake project.
Thanks to mizux and kamilcuk for your help.
Also, mizux it might be good to update the documentation to specify that "USE_SCIP=OFF" might be required to solve error arising when building using FetchContent.
Solution:
CMakeLists.txt:
cmake_minimum_required(VERSION 3.14)
project(my_proj VERSION 1.0 LANGUAGES CXX)
# Build OR-tools dependencies.
set(BUILD_DEPS ON)
# Disable SCIP solver.
set(USE_SCIP OFF)
# Fetch OR-tools library and create the alias ortools::ortools.
include(FetchContent)
FetchContent_Declare(
or-tools
GIT_REPOSITORY https://github.com/google/or-tools.git
GIT_TAG master
)
FetchContent_MakeAvailable(or-tools)
# Create a main calling operations_research::BasicExample() and link the or-tools library.
add_executable(myapp main.cpp)
target_link_libraries(myapp ortools::ortools)
main.cpp:
#include "ortools/linear_solver/linear_solver.h"
namespace operations_research {
void BasicExample() {
// Create the linear solver with the GLOP backend.
std::unique_ptr<MPSolver> solver(MPSolver::CreateSolver("GLOP"));
// Create the variables x and y.
MPVariable* const x = solver->MakeNumVar(0.0, 1, "x");
MPVariable* const y = solver->MakeNumVar(0.0, 2, "y");
LOG(INFO) << "Number of variables = " << solver->NumVariables();
// Create a linear constraint, 0 <= x + y <= 2.
MPConstraint* const ct = solver->MakeRowConstraint(0.0, 2.0, "ct");
ct->SetCoefficient(x, 1);
ct->SetCoefficient(y, 1);
LOG(INFO) << "Number of constraints = " << solver->NumConstraints();
// Create the objective function, 3 * x + y.
MPObjective* const objective = solver->MutableObjective();
objective->SetCoefficient(x, 3);
objective->SetCoefficient(y, 1);
objective->SetMaximization();
solver->Solve();
LOG(INFO) << "Solution:" << std::endl;
LOG(INFO) << "Objective value = " << objective->Value();
LOG(INFO) << "x = " << x->solution_value();
LOG(INFO) << "y = " << y->solution_value();
}
}
int main() {
operations_research::BasicExample();
return EXIT_SUCCESS;
}
Output:
$> myapp
WARNING: Logging before InitGoogleLogging() is written to STDERR
I0721 17:54:37.269460 1170927 main.cpp:17] Number of variables = 2
I0721 17:54:37.270126 1170927 main.cpp:24] Number of constraints = 1
W0721 17:54:37.273723 1170927 lp_solver.cc:163]
******************************************************************
* WARNING: Glop will be very slow because it will use DCHECKs *
* to verify the results and the precision of the solver. *
* You can gain at least an order of magnitude speedup by *
* compiling with optimizations enabled and by defining NDEBUG. *
******************************************************************
I0721 17:54:37.277882 1170927 main.cpp:34] Solution:
I0721 17:54:37.277948 1170927 main.cpp:35] Objective value = 4
I0721 17:54:37.278002 1170927 main.cpp:36] x = 1
I0721 17:54:37.278023 1170927 main.cpp:37] y = 1
Process finished with exit code 0