As other explained, the preprocessor works only on tokens, and you can only #define
a name. Read the documentation of cpp
and the C11 standard n1570.
What you want to do is very ugly (and there are few occasions where it is worthwhile). It makes your code messy, unreadable, and brittle.
Learn to use better your source code editor (you probably have some interactive replace, or interactive replace with regexp-s; if you don't, switch to a better editor like GNU emacs or vim
- and study the documentation of your editor). You could also use scripting tools like ed
, sed
, grep
, awk
etc... to help you in doing those replacements.
In a small project, replacing relevant occurrences of ->val2
(or .val2
) with ->b_obj.val2
(or .b_obj.val2
) is really easy, even if you have a hundred of them. And that keeps your code readable. Don't forget to use some version control system (to keep both old and new versions of your code).
In a large project of at least a million of lines of source code, you might ask how to find every occurrence of field usage of val2
for a given type (but you should probably name val2
well enough to have most occurrences of it be relevant; in other words, take care of the naming of your fields). That is a very different question (e.g. you could write some GCC plugin to find such occurrences and help you in replacing the relevant ones).
If you are refactoring an old and large legacy code, you need to be sure to keep it readable, and you don't want fancy macro tricks. For example, you might add some static inline
function to access that field. And it could be then worthwhile to use some better tools (e.g. a compiler plugin, some kind of C parser, etc...) to help you in that refactoring.
Keep the source code readable by human developers. Otherwise, you are shooting yourself in the foot. What you want to do is unreasonable, it decreases the readability of the code base.
I can't use Find Replace feature of other text editors, I am using VIM.
vim
is scriptable (e.g. in lua
) and accepts plugins (so if interactive replace is not enough, consider writing some vim
plugin or script to help you), and has powerful find-replace-regexp facilities. You might also use some combination of scripts to help you. In many cases they are enough. If they are not, you should explain why.
Also, you could temporarily replace the val2
field of struct a
with a unique name like val2_3TYRxW1PuK7
(or whatever is appropriate, making some unique "random-looking" name is easy). Then you run your full build (e.g. after some make clean
). The compiler would emit error messages for every place where you need to replace val2
used as a field of struct a
(but won't mind for any other occurrence of the val2
name used for some other purpose). That could help you a lot -once you have corrected your code to get rid of all errors- (especially when combined with some editor scripting) because then you just need to replace val2_3TYRxW1PuK7
with b_obj.val2
everywhere.