mszabc
mszabc

Reputation: 535

Automatic prefixing functions' names in C code

let's say I link my application with two static libraries. In both libraries we can find functions with same names but different functionality, what leads to symbol clash. My usual approach - edit source code of libraries and add unique prefix to name of each function. But I don't wanna do this manually anymore. Is there some tool or smart way to add custom prefix to all functions in selected source files? I work either on linux and windows with Visual Studio 2010, so I can use such tool on any of these two platforms.

Upvotes: 5

Views: 3001

Answers (2)

NathanTempelman
NathanTempelman

Reputation: 1387

Alright, I couldn't find you a tool so I wrote you one. I wanted to learn Ruby anyway.

#!/usr/local/bin/ruby -w

while file = ARGF.read do
  methodNames = file.scan(/\w+ (\w*) ?\([\w ,]*\);/).flatten;

  methodNames.each { |methodName|
    file.gsub!(methodName, "prefix"+methodName)}
end

You should be able to run that from command line and feed it all your source files as options. It'll take all the method names declared at the top of your file, and go through the source code prefixing "prefix" to them.

You can change prefix in the script if you like, or figure out how to feed it options as well as filenames.

For example, if you save it in a ruby file called "prefixer.rb" you'll be able to call it from command line like this:

prefixer.rb source1.c source2.c 

Or possibly

prefixer.rb *.c

Hope that does it for you, let me know if you use it.

Upvotes: 0

NathanTempelman
NathanTempelman

Reputation: 1387

Generally changing function signatures in libraries is a really bad idea. Expecially if you're working in a pre-existing code base. If somebody else is using that function, you'll break their code.

Even if it's just your own project, you probably shouldn't get in that habit.

Why don't you just fully specify the functions that clash? Instead of just letting the using Library1; using Library2; handle it, you might try explicitly specifying Library1.Function1() in ambiguious cases.

EDIT: Ah, I thought I saw C++, this answer is completely invalid without namespaces. This might help though

Edit2: objcopy seems to skirt the problem of breaking signatures for others by only prefixing a temporary copy. The link Mathias posted has a full explanation, I'll relink here for visibility

Upvotes: 0

Related Questions