1

I'm trying to link all *.o files from another folder and would like to in my Makefile do something like;

g++ *.o (folder/*.o and not folder/main.o) -o bin

Is there someway I can use somekind of simple regex here?

3
  • It can be done using Makefile. I am not pretty good in makefile. So learn it.
    – shantanu
    Jan 16, 2012 at 17:02
  • I'm already using it in a Makefile but I would like for the makefile to be independent of whats in "folder"
    – SlimJim
    Jan 16, 2012 at 17:15
  • remove folder/main.o before linking? :)
    – steabert
    Jan 18, 2012 at 8:59

3 Answers 3

3

Try g++ *.o $( echo folder/*.o |tr ' ' "\n" | egrep -v folder/main.o ), assuming none of folder/*.o have SPACES in their names.

Here's how it works:

echo folder/*.o produces a space-separated list of the filenames, with the directory.
tr ' ' "\n" changes all the spaces to newlines (giving us one filename per line, which makes egrep happy.
egrep -v folder/main.o eliminates the undesired filename from this list.
$() puts the rest of the filenames on the command line. Since $IFS defaults to SPACE, TAB, NEWLINE, we don't have to tr them back to spaces.

2
  • It works great now thanks :D Although I had to put the command within ` ` instead of $( ) since it returned nothing for some reason. Thanks again :D
    – SlimJim
    Jan 16, 2012 at 18:02
  • Perhaps you can replace for g++ *.o $( ls folder/*.o | egrep -v main.o ) for ls separates each item with a newline already.
    – Severo Raz
    Jan 16, 2012 at 18:19
1

You should use makefiles, or even better autotools, but you can do something like this:

ls folder/ | grep "*.o" | grep -v "main.o" | while read -r file; do g++ $file -o bin; done

This question would be better answered in a bash related stack site anyway haha.

1
  • Thanks man, I'm n00b on stacksites, just wondering which of them would that be, the "bash related" site?
    – SlimJim
    Feb 2, 2012 at 17:21
0

This should work:

ls -1 folder/*.o | grep -v main.o | xargs -I{} g++ {} -o bin

Explanation:

  • ls -1 folder/*.o -> list all .o files (one per line) in folder folder

  • grep -v main.o -> exclude main.o from the list

  • xargs -I{} g++ {} -o bin -> execute "g++ file -o bin"

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .