Makefiles on windows with g++, linking a library

2020-07-10 08:33发布

问题:

I've gotten fed up with MSVC++6 and how everyone is always telling me that it's a crappy compiler and such.

So now I've decided to try to use vim plus g++ and makefiles. Here's my problem; I have the following makefile:

# This is supposed to be a comment..
CC = g++
# The line above sets the compiler in use..
# The next line sets the compilation flags
CFLAGS=-c -Wall

all: main.exe

main.exe: main.o Accel.o
    $(CC) -o main.exe main.o Accel.o 

main.o: main.cpp Accel.h
    $(CC) $(CFLAGS) main.cpp

Accel.o: Accel.cpp Accel.h
    $(CC) $(CFLAGS) Accel.cpp

clean:
    del main.exe *.o

This gives an error when trying to make, because I need to link to a windows library called Ws2_32.lib, which is needed by Winsock2.h, which I include in one of my .h files.

So how do I do this? I've tried the -l option, but I can't make it work. How does it work with a path that has spaces?

回答1:

First step: locate the library you are looking for. For me, it's in :

C:\Program Files\Microsoft Visual Studio\VC98\Lib

Second step, pass that directory with -L :

LINKFLAGS=-L"C:\Program Files\Microsoft Visual Studio\VC98\Lib"

Third step, pass the name of the library with -l (lowercase L):

LINKFLAGS=-L"C:\Program Files\Microsoft Visual Studio\VC98\Lib" -lWs2_32

Then use it:

main.exe: main.o Accel.o
   $(CC) $(LINKFLAGS) -o main.exe main.o Accel.o 


回答2:

This is not an answer to your question but I suggest to use cmake . It's a multi-platform multi-build environement project file generator. The syntax of CMake files is quite simple (certainly simpler than Makefile) and it will generate Makefile or Visual Studio projects on request.

Problem with hand-coded Makefile is that very soon, your dependency tree grows so big that maintaining all the rules of what needs to build what becomes a very tedious operation. Hence, there are tons of Makefile generators (autotools, CMake) or Makefile alternatives (Scons, waf, bjam, ....)



回答3:

Use -L to specify a directory where gcc should search for libraries. Use -l (lower-case ell) to specify a library to be linked from the -L paths (and some defaults).

To escape paths with spaces, use backslashes, single or double quotes as your shell requires. See the GNU make documentation, the GNU bash documentation. See this article for info about spaces in other parts of GNU makefiles.



回答4:

You should link with library provided with the compiler. In case of cygwin you should install win32 api headers and library files, then link with libws2_32 (compiler option will look like -lws2_32).



回答5:

MSVC++6 is getting on a bit but you didn't mention how you got on with MSVC++9 and nmake (visual c++ express 2008).



回答6:

LIBS = -L"..\Microsoft SDKs\Windows\v6.0A\Lib" -lWS2_32

$(CC) ... -o ... ... $(LIBS)

This syntax worked for me!