tags:

views:

210

answers:

4

To me (a beginner in C) it looks like a program can magically access external libraries just by declaring #include "something.h" at the top of a C source file. How is it done?

I want to use the POSIX library (unistd.h). I've got the header file itself and a couple of dll's, but I can't link them together and get the compiler (GCC MinGW) to find the dll's.

What's a good tutorial on how to generate and link dll's, and how to connect dll's with C headers, and stuff like that?

+2  A: 

You are wrong in your assumptions - the header file does not give you magic access to the DLL. Header files are not libraries, and merely having the header will not allow you to call the functions it declares. In any case, MinGW comes with unistd.h - you shouldn't need any extra headers or DLLs, although note that not all POSIX features will be available in a normal Windows environment. If you want a POSIX environment on Windows, use Cygwin, not MinGW.

anon
+2  A: 

The .h file only serves to let your program know about which entry points are going to be available at compiling-linking process.

I recommend you to check your compiler documentation to know how to specify the linking .dll.

You could probably begin searching for a flag like -l to specify the .dll you are importing.

Anzurio
A: 

C is just terrible this way: connecting the right DLL's with the right .h files is entirely up to the programmer. There's a lot of programming/filesystem conventions involved, it's easy to go wrong, and it's hard for beginners to learn.

A while back I wrote a short handout on compiing and linking with Unix libraries. The details are not the same on Windows, but I hope the concepts may be useful.

Norman Ramsey
Shock! Horror! Programmers have to know what they are doing! What a ridiculous idea! But of course it's not true - MinGW, for example, arranges that the the C runtime DLL gets linke, as do all other C compilation systems I've come across. Of course, if you want to use non-standard features, you have to link the non-standard libraries.
anon
@Neil: Right. I kind of forget that some people write programs using only libc. Of course, now that glibc is an enormous bloated hog, that's a more reasonable proposition that it once was.
Norman Ramsey
A: 

While Neil's and Norman's answers are technically correct, some compilers, like MSVC, actually allow a pure #include to magically link to the correct library. This is accomplished using a special directive inside the included .h file which looks like this:

#pragma comment(lib, "library.lib")

or

#pragma comment(linker, "/DELAYLOAD:library.dll")

The compiler then embeds the comment into the generated object files (.o or .obj) and the linker extracts it and appends it to it's options.

Filip Navara