Created
May 22, 2015 04:57
-
-
Save grant-h/6d8d385b6bc968a8e690 to your computer and use it in GitHub Desktop.
Statically linking .o files with gcc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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