tags:

views:

310

answers:

3

How do I compile my C++ programs in Cygwin. I have gcc installed. What command should I use? Also, how do I run my console application when it is in a .cpp extension. I am trying to learn C++ with some little programs, but in Visual C++, I don't want to have to create a seperate project for each little .cpp file.

+4  A: 

You will need g++. Then try g++ file.cpp -o file.exe as a start. Later you can avoid much typing by learning about Makefiles.

Joy Dutta
+5  A: 

You need to use a command like:

g++ -o prog prog.cpp

That's a simple form that will turn a one-file C++ project into an executable. If you have multiple C++ files, you can do:

g++ -o prog prog.cpp part2.cpp part3.cpp

but eventually, you'll want to introduce makefiles for convenience so that you only have to compile the bits that have changed. Then you'll end up with a Makefile like:

prog: prog.o part2.o part3.o
    g++ -o prog prog.o part2.o part3.o

prog.o: prog.cpp
    g++ -c -o prog.o prog.cpp

part2.o: part2.cpp
    g++ -c -o part2.o part2.cpp

part3.o: part3.cpp
    g++ -c -o part3.o part3.cpp

And then, you'll start figuring how to write your makefiles to make them more flexible (such as not needing a separate rule for each C++ file), but that can be left for another question.

Regarding having a separate project for each C++ file, that's not necessary at all. If you've got them all in one directory and there's a simple mapping of C++ files to executable files, you can use the following makefile:

SRCS=$(wildcard *.cpp)
EXES=$(SRCS:.cpp=.exe)

all: $(EXES)

%.exe: %.cpp
    g++ -o $@ $^

Then run the make command and it will (intelligently) create all your executables. $@ is the target and $^ is the list of pre-requisites.

And, if you have more complicated rules, just tack them down at the bottom. Specific rules will be chosen in preference to the pattern rules:

SRCS=$(wildcard *.cpp)
EXES=$(SRCS:.cpp=.exe)

all: $(EXES)

%.exe: %.cpp
    g++ -o $@ $^

xx.exe: xx.cpp xx2.cpp xx3.cpp
    g++ -o $@ $^
    echo Made with special rule.
paxdiablo
Thanks. But can I create a single makefile that compiles any C++ file in the same directory instead of creating a makefile for each specific .cpp file?
Mohit Deshpande
What is the extension? .make? Or no extension like myMakefile
Mohit Deshpande
@Mohit, those makefiles do compile any cpp file to it's equivalent exe (the wildcard and the '%' pattern see to that). By convention the make file is called Makefile or makefile. You can use a different name like bob.mk but then you have to do 'make -f bob.mk all' instead of just 'make all'.
paxdiablo
A: 

if you want to use cygwin you should use the normal gcc syntax

g++ -o foobar foobar.cpp

but that doesn't really play well with Visual C++. I advise you to take a look into Eclipse CDT if you prefer using GCC over the visual C++ compiler.

RageZ