Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a program (or sed script) that will remove a function from a C file? [closed]

Tags:

git

c

I need a script where I pass a C file and a function name and it will delete that C function from the file. Is there a utility that will do this?

Basically, I'm looking to open source a library developed internally and would like to keep its history. But there are certain functions I cannot open source. I've been using git filter-branch to remove entire files that cannot be open sourced, but now I have reached the point where I need to remove certain functions from files where parts of the file may be open sourced, but others cannot. Since git filter-branch runs a command on every commit, I need something automated that will remove this function from every commit of the repository.

like image 237
David Hall Avatar asked Jun 02 '13 16:06

David Hall


2 Answers

Like lreeder, I would recommend refactoring the code so that the open-source and private stuff are in different files/libraries.

However, if that doesn't work for you, then I think you should not resort to full parsing of the C code. Instead, you could do something simple like putting the private parts of the file in between comments like //PRIVATE and //END-PRIVATE. Then you can use this ruby script to remove the private sections:

#!/usr/bin/ruby

# remove_private.rb: Removes all lines between "PRIVATE" and "END-PRIVATE"
#
# Usage 1, output to STDIO:  cat filename.c | ruby remove_private.rb
# Usage 2, output to STDIO:  ruby remove_private.rb filename.c
# Usage 3, in-place editing of file (and creating a backup): ruby -i.bak remove_private.rb filename.c

while line = ARGF.gets
  unless (line =~ /PRIVATE/)..(line =~ /END-PRIVATE/)
    puts line
  end
end

This uses some magical and convenient features of ruby to make the code short, but I think it will be much easier to debug and maintain than a full C parser. Also, the developers can easily see which functions are private while they are working on the code. I did something very similar to this for a project I was working on where we wanted to release part of a Makefile but not the whole thing. Maybe you could rewrite it in your company's favorite scripting language.

like image 153
David Grayson Avatar answered Oct 13 '22 08:10

David Grayson


Can't you refactor all the non-open C functions into a separate file/library? This is work, but would be cleaner than changing your source code for every public release, and probably easier to maintain in the long term.

If refactoring is not an option, I found a perl-based C source code parser at http://search.cpan.org/~jtbraun/Parse-RecDescent-1.967009/demo/demo_another_Cgrammar.pl. Looks like with some hacking, it could filter out unwanted functions.

like image 24
lreeder Avatar answered Oct 13 '22 09:10

lreeder