Ask Your Question
1

Getting $Ros_distro in c++ code.

asked 2021-11-19 11:26:34 -0500

AB4147 gravatar image

Hi, I want to ask like is there a way to get the ROS_DISTRO in c++, cz I want to run specific C++ code when ros_distro is melodic, and else if noetic then this code. Ubuntu: 20.04 Thank You.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-11-19 12:17:08 -0500

osilva gravatar image

I am sure there is a simpler way, but this is how I will do if I am in a pinch. Since echo $ROS_DISTRO will give me the information, then I will use a program to read the output of this command:

From this example I will make a slight modification accordingly.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

string GetStdoutFromCommand(string cmd) {

  string data;
  FILE * stream;
  const int max_buffer = 256;
  char buffer[max_buffer];
  cmd.append(" 2>&1");

  stream = popen(cmd.c_str(), "r");
  if (stream) {
    while (!feof(stream))
      if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer);
    pclose(stream);
  }
  return data;
}

int main() {

  string ros_version = GetStdoutFromCommand("echo $ROS_DISTRO");
  cout << "ROS version: " << ros_version << endl;
  return 0;
}
edit flag offensive delete link more

Comments

1

ROS_DISTRO is an environment variable.

Why not just read the environment variable with the appropriate functions? See std::getenv(..).

And actually, using conditional compilation might even be better.

gvdhoorn gravatar image gvdhoorn  ( 2021-11-19 13:02:21 -0500 )edit

@gvdhoorn that's way better than what I propose!

osilva gravatar image osilva  ( 2021-11-19 13:20:48 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-11-19 11:26:34 -0500

Seen: 36 times

Last updated: Nov 19 '21