Delete Unnecessary Macro or Function From Source Code

February 9, 2014

This could easily be done with sed or a simple perl script, so let this just be an example. This is an example program that's basically an exercise in using std::string.

Anyhow, let me see if I can explain what this does seeing that I needed it for a very specific purpose. I had a very large code base that used several function calls and macros that I wanted to remove, but I wanted to keep the expression that was being passed to the function.

For example, I had the following C code:
if (EXPECT(x < 5))
I wanted to convert it to:
if (x < 5)

So, compile the following app and use a script to run it over a code base and you have it fixed. This could just as well be a starting point for doing some other things on a massive scale quickly. If I was going to do this a different way, outside of using a script, I'd probably go after regex.

/*
 * delfunc.cpp - Delete an unecessary function/macro from being used.
 */
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
 
using namespace std;
 
static void usage(const char* base)
{
   cout << "usage: " << base << " FILENAME FUNCTION" << endl;
}
 
int main(int argc, char** argv)
{
   if (argc != 3)
   {
      usage(argv[0]);
      return 1;
   }
 
   ifstream in(argv[1]);
 
   if (in.good())
   {
      bool changed = false;
      std::string str((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
 
      string::size_type start = 0;
 
      while (start != string::npos)
      {
	 start = str.find(argv[2],start);
	 if (start == string::npos)
	 {
	    break;
	 }
 
	 string::size_type end = str.find("(",start);
	 string::size_type close = str.find(")",end);
 
	 if (end != string::npos && close != string::npos)
	 {
	    str.erase(start,end-start+1);
	    str.erase(close-(end-start)-1,1);
	    changed = true;
	 }
      }
 
      in.close();
 
      if (changed)
      {
	 ofstream out(argv[1],ofstream::trunc);
	 if (out.good())
	 {
	    out << str;
	    out.close();
	 }
	 else
	 {
	    return 1;
	 }
      }
   }
   else
   {
      return 1;
   }
 
   return 0;
}
Here's an example makefile.
CPPFLAGS = -O3
 
all: delfunc
 
delfunc: delfunc.cpp
	$(CXX) $(CPPFLAGS) $< -o $@
 
clean:
	rm -f delfunc

Related Posts