Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile C++ with Cygwin

Tags:

gcc

cygwin

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.

like image 264
Mohit Deshpande Avatar asked Nov 18 '09 02:11

Mohit Deshpande


2 Answers

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.
like image 132
paxdiablo Avatar answered Oct 11 '22 12:10

paxdiablo


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.

like image 34
Joy Dutta Avatar answered Oct 11 '22 13:10

Joy Dutta