Using #defines inside other #defines

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
#define NUM_CORES 2
#define COMMAND_STRING ("/bin/awesome -mt NUM_CORES -i "+fin+" -o "+fout).c_str()

using namespace std;

int main() {
	string fin = "fin here";
	string fout = "fout here";
	cout << COMMAND_STRING;
	return 0;
}

This outputs:
/bin/awesome -mt NUM_CORES -i fin here -o fout here
How can I get NUM_CORES to say 2 in the output string?

You probably shouldn't be using macros for this. A better solution would be to make a function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <sstream>

//...

static const int num_cores = 2;

string command_string(const string& fin,const string& fout)
{
  stringstream s;
  s << "/bin/awesome -mt " << num_cores << " -i " << fin << " -o " << fout;
  return s.str();
}

int main()
{
  // ...
  cout << command_string( fin, fout );
}
You can't interpolate a variable twice, yea perl/shell for teaching me this!
1
2
3
$yea = 'Perl';
$var = '$yea';
print "$var is Awesome!\n";
$yea is Awsome!


Okay... So basically the preprocessor macros only interpolate once.
Technically, there's no reason why line 3 couldn't print "Perl is awesome!\n". I wrote a language once that did just that.
Well with a simple edit:
1
2
3
4
$yea = 'Perl';
$var = "$yea";
print "$var is Awesome!\n";
#Did you find the difference? (It's not this comment)
Perl is Awesome!

However that defeats the purpose of this example.

helios wrote:
I wrote a language once that did just that.
Not that I'm trying to take away from the accomplishment, but why?
Last edited on
Part of the language required me to allow something equivalent to this:
print $foo bar
So I decided to just solve a more general problem and make the part after the print a string and allow this:
bar="$foo $bar"
Avoiding infinite recursion was easy. Just store previous levels in a stack and check that no variable is traversed more than once in the same branch.
Last edited on
Topic archived. No new replies allowed.