Yes, you can compile an ELF executable with no library dependencies using gcc. Such an executable is called a statically linked executable because it includes all the necessary code from libraries directly within the executable itself, rather than relying on shared libraries at runtime.
To create a statically linked executable with gcc, you need to use the -static flag. Here is an example:
gcc -static -o test test.c
Explanation:
-
gcc:
- The GNU Compiler Collection, which includes the C compiler.
-
-static:
- This flag tells
gcc to link the executable statically. It embeds the necessary library code directly into the executable, eliminating runtime dependencies on shared libraries.
-
-o test:
- This specifies the output filename for the executable. In this case the output file will be named
test.
-
test.c:
- This is your source code file.
Example
Assume you have a simple test.c file:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
To compile this file into a statically linked executable, you would run:
gcc -static -o test test.c
Verifying the Output
After compiling, you can use the file command to verify that the executable has no library dependencies:
file test
The output should be similar to:
test: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, BuildID[sha1]=somehash, for GNU/Linux 3.2.0, not stripped
Notice the statically linked part, indicating that there are no dynamic library dependencies.
Additional Notes
- Standard Libraries:
- Even when using
-static, some standard libraries like libc are still linked. However, they are included directly in the executable rather than being dynamically linked.