Skip to content

Instantly share code, notes, and snippets.

@je-so
Created December 7, 2013 07:08
Show Gist options
  • Save je-so/7838185 to your computer and use it in GitHub Desktop.
Save je-so/7838185 to your computer and use it in GitHub Desktop.
Simulate package visibility of functions of different modules contained in a single directory.
#!/bin/bash
# BUILD library which contains all modules of the package
echo "Build package.o from module1.c and module2.c"
gcc -c -o module1.o module1.c
gcc -c -o module2.o module2.c
ld -o package.o -r module1.o module2.o
symbols=(`nm package.o`)
for((i=0;i<${#symbols[*]};i=i+1)) do
if [ "${symbols[$i]}" != "T" ]; then continue; fi
function_name=${symbols[$((i+1))]}
if [ "${function_name#private}" = "$function_name" ]; then continue; fi
echo "Change function '$function_name' to package scope (private)"
objcopy -L "$function_name" package.o
done
echo "Generate main.c and link it with package.o"
echo "main() calls public_function from module1.c in package.o"
echo "#include <stdio.h>" > main.c
echo "#include \"module1.h\"" >> main.c
echo >> main.c
echo "int main(int argc, const char* argv[])" >> main.c
echo "{" >> main.c
echo " public_function();" >> main.c
echo " return 0;" >> main.c
echo "}" >> main.c
gcc -o main main.c package.o
echo "::Start main::"
./main
echo "::End main::"
echo
echo "Generate main.c and link it with package.o"
echo "main() now tries to call private_function from module2.c in package.o"
echo "This will generate a compiler error !"
gcc -o main "-Dpublic_function=private_function" main.c package.o
#include <stdio.h>
#include "module1.h" // header of this module
#include "module2.h" // contains private_function
void public_function()
{
printf("enter public_function()\n");
private_function();
printf("exit public_function()\n");
}
#ifndef PACKAGE_MODULE1_HEADER
#define PACKAGE_MODULE1_HEADER
void public_function(void);
#endif
#include <stdio.h>
#include "module2.h" // header of this module
void private_function()
{
printf("enter private_function()\n");
printf("exit private_function()\n");
}
#ifndef PACKAGE_MODULE2_HEADER
#define PACKAGE_MODULE2_HEADER
void private_function(void);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment