Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Export formatted list of symbols defined in a C/C++ library
#!/usr/bin/env ruby
#==============================================================================
#
# Searches for a library either local or on the system and prints out a sorted
# list of all exported symbols found within it. (UNIX-like systems only)
#
# Useful for creating a wrapper/bindings for a C/C++ library.
#
# Example: exportsym tar
# - Searches system for tar.so, tar.a, libtar.so, libtar.a, etc, etc.
# - Outputs list of exported functions
#
#==============================================================================
lib = ARGV[0]
unless lib
puts 'No library name specified'
exit
end
SEARCH_PATHS = ['.', '/usr/lib', '/lib', '/var/lib']
EXTENSIONS = ['.so', '.a']
path = nil
SEARCH_PATHS.product(EXTENSIONS).each do |c|
dir = c.first
ext = c.last
path = File.join(dir, lib + ext)
break if File.exist?(path)
unless /^lib/.match(lib)
path = File.join(dir, 'lib' + lib + ext)
break if File.exist?(path)
end
path = nil
end
if path.nil?
puts "Unable to locate library \"#{lib}\""
exit
end
result = `nm -D --defined-only '#{path}' -f bsd`
list = []
result.split("\n").map(&:chomp).each do |line|
match = /^[\h]+ ([\w]) (.+)/.match(line)
unless match
warn("failed to match '${line}'")
next
end
list << $2
end
list.sort!
list.each { |item| puts item }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.