Reputation: 51
I recently started compiling/linking my C files by hand using the gcc command. However it requires all of the source files to be typed at the end of the command. When there are many files to compile/link it can be boring. That's why I had the idea of making a bash alias for the command which would directly type all *.h and *.c files of the folder.
My line in .bashrc is this:
alias compile='ls *.c *.h | gcc -o main'
I found it to work some times but most of the time compile will return this :
gcc: fatal error: no input files
compilation terminated.
I thought that pipe would give the results of ls *.c *.h as arguments to gcc but it doesn't seem to work that way. What am I doing wrong? Is there a better way to achieve the same thing?
Thanks for helping
Upvotes: 5
Views: 2035
Reputation: 126867
There are several misconceptions here:
ls
, it's the shell that performs their expansion on the command line;.c
files, which in turn may include headers.Armed with this knowledge, you'll understand that the correct command something like
gcc -o main *.c
Actually we can do better: first of all, you'll want to change the *.c
to ./*.c
; this prevents files whose name start with a -
from being interpreted as command line options.
Most importantly, you should really enable the compiler warnings, they can be life saver. You'll want to add -Wall
and -Wextra
.
gcc -Wall -Wextra -o main ./*.c
Finally, it's worth saying that by default you are compiling with optimizations disabled. If you are debugging that's OK, but you want also to add -g
to have an executable usable in debugging; otherwise, if the target is speed you should at least add -O2
.
Upvotes: 4
Reputation: 81012
A pipe does not create command line arguments. A pipe feeds standard input.
You need xargs
to convert standard input to command line arguments.
But you don't need (or want) xargs
or ls
or standard input here at all.
If you just want to compile every .c
file into your executable then just use:
gcc -o main *.c
(You don't generally need .h
files on gcc
command lines.)
As Kay points out in the comments the pedantically correct and safer version of the above command is (and I don't intend this in a pejorative fashion):
gcc -o main ./*.c
See Filenames and Pathnames in Shell: How to do it Correctly for an extensive discussion of the various issues here.
That being said you can use any of a number of tools to save you from needing to do this and from needing to rebuild everything when only some things change.
Tools like make
or its many clones, "front-ends" (e.g. the autotools, cmake) or replacements (tup, scons, cons, and about a million other tools).
Upvotes: 7
Reputation: 53
Have you tried using a makefile? It sounds like that might be more efficient for what you're trying to do.
If you really want to do it with BASH aliases, you have to use xargs to get standard input to command line arguments.
Upvotes: 4