c++roslaunch

How to run launch file in ROS from C++ .cpp file


I would like to know how can I run launch file using a c++ file. I want to run different launch file depending on the if statement.

if(case1){
 run launch_file_1.launch}
if(case2){
 run launch_fie_2.launch}

Solution

  • Using the cstdlib library we can do this. You are basically creating a command line command using c++

    #include <cstdlib> // for system()
        
        int main(int argc, char** argv)
        {
          // Call roslaunch command to run your launch file
          std::string launch_file_path = "/path/to/your/launch/file.launch"; // Replace with the path to your actual launch file
          std::string command = "roslaunch " + launch_file_path;
          int result = system(command.c_str());
          if (result == -1)
          {
            ROS_ERROR("Failed to execute roslaunch command");
            return 1;
          }
        
          return 0;
        }