insomniacjunkie insomniacjunkie - 5 months ago 11
Perl Question

Script to Find CPP Macro Object and Replace Token

Okay, I have tried to do this in Perl and have had little to no success...

Inside of a .cpp file I have the following text...

#define VARIABLE_A 32


And I wish to replace this with some other number

#define VARIABLE_A 123


I would like to be able to run this through my command-line such as:

change_variable_a 123


What is the easiest way to achieve this? BASH or Perl preferred.

The code I have now is garbage. I am going about it completely wrong trying to pass parameters through a bash script into a perl one-liner.

Okay here is what I have.

perl -MPOSIX -pe's/(\d+)/@ARGV[0]/e if /define\s+VARIABLE_A\s+\d+/' file.h > file.h.2
mv -f file.h.2 file.h

Answer

When you recompile, you can use the -D option to set a value on the command line (at least in gcc and clang; presumably others). So the simplest solution is to just define VARIABLE_A on the command line.

gcc -D VARIABLE_A=123 file.cc

If you want to have a default, you just need to have something in your code to define VARIABLE_A when it hasn't been set on the command line.

#ifndef VARIABLE_A
#define VARIABLE_A 32
#endif