Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
cpp_example.cc File Reference
#include <cstddef>
#include <cstdlib>
#include <iostream>
#include <string>
#include "absl/status/status.h"
#include "ortools/base/init_google.h"
#include "ortools/math_opt/core/c_api/solver.h"
#include "ortools/math_opt/model.pb.h"
#include "ortools/math_opt/parameters.pb.h"
#include "ortools/math_opt/result.pb.h"
#include "ortools/math_opt/sparse_containers.pb.h"

Go to the source code of this file.

Functions

int main (int argc, char **argv)
 

Function Documentation

◆ main()

int main ( int argc,
char ** argv )

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Demonstrates how to call the MathOpt C API defined in solver.h from C++.

At a high level, the example:

  • builds a ModelProto in C++,
  • serializes the model to binary,
  • calls MathOptSolve() from the C-API on the model binary, which outputs a SolveResultProto in binary,
  • parses a C++ SolveResultProto from the binary,
  • prints some key parts of the SolveResultProto.

Actual C++ users should use MathOpt's various C++ APIs. This is just a demonstration of how the C API is intended to be used (from any language that an interoperate with C). This example solves the optimization problem: max x x in [0, 1] and then prints out the termination reason and objective value.

Create a serialized ModelProto for the problem.

Pick a solver.

Set up the output arguments for MathOptSolve()

Call the C API to do solve the model and populate the output arguments.

If MathOptSolve() failed, print the error and abort.

If you handle the error instead of crashing, be sure to free status_msg.

Recover the SolveResultProto from the output arguments (stored as a serialized proto).

Print out the desired output.

Clean up any memory allocated by MathOptSolve(). Note that invoking these functions on nullptr is safe.

Definition at line 45 of file cpp_example.cc.