-
-
Save RandyMcMillan/37360cecd8558bac19b6cce01a085f66 to your computer and use it in GitHub Desktop.
Bash-C Hello World: Compile and run a C program from a single Bash script
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/bash | |
# bash_c_example.sh | |
# Directory to store the C source file and the executable | |
EXAMPLES_DIR="$HOME/bash_c_examples" | |
# Ensure the directory exists, create it if not | |
mkdir -p "$EXAMPLES_DIR" | |
# Check if hello_world.c and hello_world executable already exist | |
if [[ -f "$EXAMPLES_DIR/hello_world.c" && -x "$EXAMPLES_DIR/hello_world" ]]; then | |
# Run the existing executable | |
echo "(Running existing hello_world executable)" | |
"$EXAMPLES_DIR/hello_world" | |
else | |
# Define the C code with "Hello, World!" inside a docstring | |
CODE=$(cat <<EOF | |
#include <stdio.h> | |
int main() { | |
printf("\\nHello, World!\\n\\n"); | |
return 0; | |
} | |
EOF | |
) | |
# Create a C source file with the defined code in the specified directory | |
echo "$CODE" > "$EXAMPLES_DIR/hello_world.c" | |
# Change directory to the examples directory | |
cd "$EXAMPLES_DIR" || exit | |
# Compile the C source file using GCC | |
gcc -o hello_world hello_world.c | |
# Run the compiled executable | |
echo "(Running newly compiled hello_world executable)" | |
./hello_world | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment