Skip to content

Instantly share code, notes, and snippets.

@grant-h
Created May 22, 2015 04:57
Show Gist options
  • Save grant-h/6d8d385b6bc968a8e690 to your computer and use it in GitHub Desktop.
Save grant-h/6d8d385b6bc968a8e690 to your computer and use it in GitHub Desktop.
Statically linking .o files with gcc
#!/bin/sh
set -e
cat > libtest.c <<EOF
#include <stdio.h>
void test_function(int arg)
{
printf("Calling test_function(%d)\n", arg);
}
EOF
cat > test.c <<EOF
#include <stdio.h>
// provided by libtest.c
void test_function(int arg);
int main(int argc, char * argv[])
{
printf("Calling a library function\n");
test_function(42);
return 0;
}
EOF
# Compile and pack the library
# Make sure to include '-c' to prevent linking
gcc -o libtest.o -c libtest.c
echo "Packed object files:"
ar cvr libtest.a libtest.o
# Now statically link the library
gcc -o test test.c -L${PWD} -ltest
echo -e "\nLibraries used:"
ldd test
echo -e "\nResult:"
./test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment