Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question
    
It can be done using Makefile. I am not pretty good in makefile. So learn it. –  shantanu Jan 16 '12 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 '12 at 17:15
    
remove folder/main.o before linking? :) –  steabert Jan 18 '12 at 8:59

3 Answers 3

up vote 3 down vote accepted

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.

share|improve this answer
    
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 '12 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. –  Wolter Hellmund Jan 16 '12 at 18:19

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.

share|improve this answer
    
Thanks man, I'm n00b on stacksites, just wondering which of them would that be, the "bash related" site? –  SlimJim Feb 2 '12 at 17:21

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"

share|improve this answer
1  
Niffty commands, thanks :) –  SlimJim Feb 2 '12 at 17:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.