Programming Questions How do I contribute a package? If you are willing to be a package maintainer, great! We urgently need volunteers to prepare and maintain packages, because the priority of the Cygwin Team is Cygwin itself. The Cygwin Package Contributor's Guide at details everything you need to know about being a package maintainer. The quickest way to get started is to read the Initial packaging procedure, script-based section on that page. The generic-build-script found there works well for most packages. For questions about package maintenance, use the cygwin-apps mailing list (start at ) after searching and browsing the cygwin-apps list archives, of course. Be sure to look at the Submitting a package checklist at before sending an ITP (Intent To Package) email to cygwin-apps. You should also announce your intentions to the general cygwin list, in case others were thinking the same thing. How do I contribute to Cygwin? If you want to contribute to Cygwin itself, see . Why are compiled executables so huge?!? By default, gcc compiles in all symbols. You'll also find that gcc creates large executables on UNIX. If that bothers you, just use the 'strip' program, part of the binutils package. Or compile with the -s option to gcc. What do I have to look out for when porting applications to 64 bit Cygwin? The Cygwin x86_64 toolchain is using the LP64 data model. That means, in contrast to Windows, which uses an LLP64 data model, sizeof(long) != sizeof(int), just as on Linux. For comparison: Cygwin Windows Cygwin Linux x86_64 Linux Windows x86_64 i686 sizeof(int) 4 4 4 sizeof(long) 4 4 8 sizeof(size_t) 4 8 8 sizeof(void*) 4 8 8 This difference can result in interesting problems, especially when using Win32 functions, especially when using pointers to Windows datatypes like LONG, ULONG, DWORD. Given that Windows is LLP64, all of the aforementioned types are 4 byte in size, on 32 as well as on 64 bit Windows, while `long' on 64 bit Cygwin is 8 bytes. Take the example ReadFile: ReadFile (HANDLE, LPVOID, DWORD, LPDWORD, LPOVERLAPPED); In the 32 bit Cygwin and Mingw environments, as well as in the 64 bit Mingw environment, it is no problem to substitute DWORD with unsigned long: unsigned long number_of_bytes_read; [...] ReadFile (fhdl, buf, buflen, &number_of_bytes_read, NULL); However, in 64 bit Cygwin, using LP64, number_of_bytes_read is 8 bytes in size. But since ReadFile expects a pointer to a 4 byte type, the function will only change the lower 4 bytes of number_of_bytes_read on return, while the content of the upper 4 bytes stays undefined. Here are a few donts which should help porting applications from the known ILP32 data model of 32 bit Cygwin, to the LP64 data model of 64 bit Cygwin. Note that these are not Cygwin-only problems. Many Linux applications suffered the same somewhat liberal handling of datatypes when the AMD64 CPU was new. Don't mix up int and long in printf/scanf. This: int i; long l; printf ("%d %ld\n", l, i); may not print what you think it should. Enable the gcc options -Wformat or -Wall, which warn about type mismatches in printf/scanf functions. Using -Wall (optionally with -Werror to drive the point home) makes a lot of sense in general, not only when porting code to a new platform. Don't mix int and long pointers. long *long_ptr = (long *) &my_int; /* Uh oh! */ *long_ptr = 42; The assignment will write 8 bytes to the address of my_int. Since my_int is only 4 bytes, something else gets randomly overwritten. Finding this kind of bug is very hard, because you will often see a problem which has no immediate connection to the actual bug. Don't mix int and pointers at all! This will not work as expected anymore: void *ptr; printf ("Pointer value is %x\n", ptr); %x denotes an int argument. The value printed by printf is a 4 byte value, so on x86_64 the printed pointer value is missing its upper 4 bytes; the output is very likely wrong. Use %p instead, which portable across architectures: void *ptr; printf ("Pointer value is %p\n", ptr); Along the same lines don't use the type int in pointer arithmetic. Don't cast pointers to int, don't cast pointer differences to int, and don't store pointer differences in an int type. Use the types intptr_t, uintptr_t and ptrdiff_t instead, they are designed for performing architecture-independent pointer arithmetic. Don't make blind assumptions about the size of a POSIX type. For instance, time_t is 8 bytes on 64 bit Cygwin, while it is (still, at the time of writing this) 4 bytes on 32 bit Cygwin, since time_t is based on the type long. Don't use functions returning pointers without declaration. For instance printf ("Error message is: %s\n", strerror (errno)); This code will crash, unless you included string.h. The implicit rule in C is that an undeclared function is of type int. But int is 4 byte and pointers are 8 byte, so the string pointer given to printf is missing the upper 4 bytes. Don't use C base types together with Win32 functions. Keep in mind that DWORD, LONG, ULONG are not the same as long and unsigned long. Try to use only Win32 datatypes in conjunction with Win32 API function calls to avoid type problems. See the above ReadFile example. Windows functions in printf calls should be treated carefully as well. This code is common for 32 bit code, but probably prints the wrong value on 64 bit: printf ("Error message is: %lu\n", GetLastError ()); Using gcc's -Wformat option would warn about this. Casting to the requested base type helps in this case: printf ("Error message is: %lu\n", (unsigned long) GetLastError ()); Don't mix Windows datatypes with POSIX type-specific MIN/MAX values. unsigned long l_max = ULONG_MAX; /* That's right. */ ULONG w32_biggest = ULONG_MAX; /* Hey, wait! What? */ ULONG w32_biggest = UINT_MAX; /* Ok, but borderline. */ Again, keep in mind that ULONG (or DWORD) is not unsigned long but rather unsigned int on 64 bit. My project doesn't build at all on 64 bit Cygwin. What's up? Typically reasons for that are: __CYGWIN32__ is not defined in the 64 bit toolchain. This may hit a few projects which are around since before Y2K. Check your project for occurences of __CYGWIN32__ and change them to __CYGWIN__, which is defined in the Cygwin toolchain since 1998, to get the same Cygwin-specific code changes done. The project maintainers took it for granted that Cygwin is running only on i686 CPUs and the code is making this assumption blindly. You have to check the code for such assumptions and fix them. The project is using autotools, the config.sub and config.guess files are hopelessly outdated and don't recognize x86_64-{pc,unknown}-cygwin as valid target. Update the project configury (cygport will do this by default) and try again. The project uses Windows functions on Cygwin and it's suffering from the problems described in the preceeding FAQ entry. In all of this cases, please make sure to fix that upstream, or send your patches to the upstream maintainers, so the problems get fixed for the future. Why is __CYGWIN64__ not defined for 64 bit? There is no __CYGWIN64__ because we would like to have a unified way to handle Cygwin code in portable projects. Using __CYGWIN32__ and __CYGWIN64__ only complicates the code for no good reason. Along the same lines you won't find predefined macros __linux32__ and __linux64__ on Linux. If you really have to differ between 32 and 64 bit in some way, you have three choices. If your code depends on the CPU architecture, use the predefined compiler definition for the architecture, like this: #ifdef __CYGWIN__ # ifdef __x86_64__ /* Alternatively __x86_64, __amd64__, __amd64 */ /* Code specific for AMD64 CPU */ # elif __X86__ /* Code specific for ix86 CPUs */ # else # error Unsupported Architecture # endif #endif If your code depends on differences in the data model, you should consider to use the __LP64__ definition instead: #ifdef __CYGWIN__ # ifdef __LP64__ /* Alternatively _LP64 */ /* Code specific for 64 bit CPUs */ # else /* Code specific for 32 bit CPUs */ # endif #endif If your code uses Windows functions, and some of the functionality is 64 bit Windows-specific, use _WIN64, which is defined on 64 bit Cygwin, as soon as you include windows.h. This should only be used in the most desperate of occasions, though, and only if it's really about a difference in Windows API functionality! #ifdef __CYGWIN__ # ifdef _WIN64 /* Code specific for 64 bit Windows */ # else /* Code specific for 32 bit Windows */ # endif #endif Where is glibc? Cygwin does not provide glibc. It uses newlib instead, which provides much (but not all) of the same functionality. Porting glibc to Cygwin would be difficult. Where is Objective C? Support for compiling Objective C is available in the gcc{4}-objc package; resulting binaries will depend on the libobjc2 package at runtime. Why does my make fail on Cygwin with an execvp error? Beware of using non-portable shell features in your Makefiles (see tips at ). Errors of make: execvp: /bin/sh: Illegal Argument or make: execvp: /bin/sh: Argument list too long are often caused by the command-line being to long for the Windows execution model. To circumvent this, mount the path of the executable using the -X switch to enable cygexec for all executables in that folder; you will also need to exclude non-cygwin executables with the -x switch. Enabling cygexec causes cygwin executables to talk directly to one another, which increases the command-line limit. To enable cygexec for /bin and /usr/bin, you can add or change these entries in /etc/fstab: C:/cygwin/bin /bin ntfs binary,cygexec 0 0 C:/cygwin/bin /usr/bin ntfs binary,cygexec 0 0 If you have added other non-Cygwin programs to a path you want to mount cygexec, you can find them with a script like this: #!/bin/sh cd /bin; for f in `find . -type f -name '*.exe'`; do cygcheck $f | (fgrep -qi cygwin1.dll || echo $f) done See for more information on using mount. How can I use IPC, or why do I get a Bad system call error? Try running cygserver. Read . If you're trying to use PostgreSQL, also read /usr/share/doc/Cygwin/postgresql-*.README. Why the undefined reference to WinMain@16? If you're using gcc, try adding an empty main() function to one of your sources. Or, perhaps you have -lm too early in the link command line. It should be at the end: bash$ gcc hello.c -lm bash$ ./a.exe Hello World! works, but bash$ gcc -lm hello.c /c/TEMP/ccjLEGlU.o(.text+0x10):hello.c: multiple definition of `main' /usr/lib/libm.a(libcmain.o)(.text+0x0):libcmain.c: first defined here /usr/lib/libm.a(libcmain.o)(.text+0x6a):libcmain.c: undefined reference to `WinMain@16' collect2: ld returned 1 exit status If you're using GCJ, you need to pass a "--main" flag: gcj --main=Hello Hello.java How do I use Win32 API calls? Cygwin tools require that you explicitly link the import libraries for whatever Win32 API functions that you are going to use, with the exception of kernel32, which is linked automatically (because the startup and/or built-in code uses it). For example, to use graphics functions (GDI) you must link with gdi32 like this: gcc -o foo.exe foo.o bar.o -lgdi32 or (compiling and linking in one step): gcc -o foo.exe foo.c bar.c -lgdi32 The regular setup allows you to use the option -mwindows on the command line to include a set of the basic libraries (and also make your program a GUI program instead of a console program), including user32, gdi32 and comdlg32. It is a good idea to put import libraries last on your link line, or at least after all the object files and static libraries that reference them. There are a few restrictions for calls to the Win32 API. For details, see the User's Guide section Restricted Win32 environment, as well as the User's Guide section Using the Win32 file API in Cygwin applications. How do I compile a Win32 executable that doesn't use Cygwin? The compilers provided by the mingw-gcc, mingw64-i686-gcc, and mingw64-x86_64-gcc packages link against standard Microsoft DLLs instead of Cygwin. This is desirable for native Windows programs that don't need a UNIX emulation layer. This is not to be confused with 'MinGW' (Minimalist GNU for Windows), which is a completely separate effort. That project's home page is . Can I build a Cygwin program that does not require cygwin1.dll at runtime? No. If your program uses the Cygwin API, then your executable cannot run without cygwin1.dll. In particular, it is not possible to statically link with a Cygwin library to obtain an independent, self-contained executable. If this is an issue because you intend to distribute your Cygwin application, then you had better read and understand , which explains the licensing options. Unless you purchase a special commercial license from Red Hat, then your Cygwin application must be Open Source. Can I link with both MSVCRT*.DLL and cygwin1.dll? No, you must use one or the other, they are mutually exclusive. How do I make the console window go away? The default during compilation is to produce a console application. It you are writing a GUI program, you should either compile with -mwindows as explained above, or add the string "-Wl,--subsystem,windows" to the GCC command line. Why does make complain about a "missing separator"? This problem usually occurs as a result of someone editing a Makefile with a text editor that replaces tab characters with spaces. Command lines must start with tabs. This is not specific to Cygwin. Why can't we redistribute Microsoft's Win32 headers? Subsection 2.d.f of the `Microsoft Open Tools License agreement' looks like it says that one may not "permit further redistribution of the Redistributables to their end users". We take this to mean that we can give them to you, but you can't give them to anyone else, which is something that we can't agree to. Fortunately, we have our own Win32 headers which are pretty complete. How do I use cygwin1.dll with Visual Studio or MinGW? Before you begin, note that Cygwin is licensed under the GNU GPL (as indeed are many other Cygwin-based libraries). That means that if your code links against the Cygwin dll (and if your program is calling functions from Cygwin, it must, as a matter of fact, be linked against it), you must apply the GPL to your source as well. Of course, this only matters if you plan to distribute your program in binary form. For more information, see . If that is not a problem, read on. If you want to load the DLL dynamically, read winsup/cygwin/how-cygtls-works.txt and the sample code in winsup/testsuite/cygload to understand how this works. The short version is: Make sure you have 4K of scratch space at the bottom of your stack. Invoke cygwin_dll_init(): HMODULE h = LoadLibrary("cygwin1.dll"); void (*init)() = GetProcAddress(h, "cygwin_dll_init"); init(); If you want to link statically from Visual Studio, to my knowledge none of the Cygwin developers have done this, but we have this report from the mailing list that it can be done this way: Use the impdef program to generate a .def file for the cygwin1.dll (if you build the cygwin dll from source, you will already have a def file) impdef cygwin1.dll > cygwin1.def Use the MS VS linker (lib) to generate an import library lib /def=cygwin1.def /out=cygwin1.lib Create a file "my_crt0.c" with the following contents #include <sys/cygwin.h> #include <stdlib.h> typedef int (*MainFunc) (int argc, char *argv[], char **env); void my_crt0 (MainFunc f) { cygwin_crt0(f); } Use gcc in a Cygwin prompt to build my_crt0.c into a DLL (e.g. my_crt0.dll). Follow steps 1 and 2 to generate .def and .lib files for the DLL. Download crt0.c from the cygwin website and include it in your sources. Modify it to call my_crt0() instead of cygwin_crt0(). Build your object files using the MS VC compiler cl. Link your object files, cygwin1.lib, and my_crt0.lib (or whatever you called it) into the executable. Note that if you are using any other Cygwin based libraries that you will probably need to build them as DLLs using gcc and then generate import libraries for the MS VC linker. Thanks to Alastair Growcott (alastair dot growcott at bakbone dot co dot uk) for this tip. How do I link against a .lib file? If your .lib file is a normal static or import library with C-callable entry points, you can list foo.lib as an object file for gcc/g++, just like any *.o file. Otherwise, here are some steps: Build a C file with a function table. Put all functions you intend to use in that table. This forces the linker to include all the object files from the .lib. Maybe there is an option to force LINK.EXE to include an object file. Build a dummy 'LibMain'. Build a .def with all the exports you need. Link with your .lib using link.exe. or Extract all the object files from the .lib using LIB.EXE. Build a dummy C file referencing all the functions you need, either with a direct call or through an initialized function pointer. Build a dummy LibMain. Link all the objects with this file+LibMain. Write a .def. Link. You can use these methods to use MSVC (and many other runtime libs) with Cygwin development tools. Note that this is a lot of work (half a day or so), but much less than rewriting the runtime library in question from specs... Thanks to Jacob Navia (root at jacob dot remcomp dot fr) for this explanation. How do I build Cygwin on my own? First, you need to make sure you have the necessary build tools installed; you at least need gcc-g++, make, perl, cocom, gettext, gettext-devel, and zlib-devel. Building for 32-bit Cygwin also requires libiconv, mingw64-i686-gcc-g++, mingw64-i686-zlib, and mingw64-x86_64-gcc-core. Building for 64-bit Cygwin also requires libiconv-devel, mingw64-x86_64-gcc-g++, and mingw64-x86_64-zlib. If you want to run the tests, dejagnu is also required. Normally, building ignores any errors in building the documentation, which requires the dblatex, docbook-xml45, docbook-xsl, and xmlto packages. For more information on building the documentation, see the README included in the cygwin-doc package. Next, get the Cygwin source. Ideally, you should check out what you need from GIT (). This is the preferred method for acquiring the sources. Otherwise, if you are trying to duplicate a cygwin release then you should download the corresponding source package (cygwin-x.y.z-n-src.tar.bz2). You must build cygwin in a separate directory from the source, so create something like a build/ directory. Assuming you checked out the source in /oss/src/, and you also want to install to the temporary location install: mkdir /oss/build mkdir /oss/install cd build (/oss/src/configure --prefix=/oss/install -v; make) >& make.out make install > install.log 2>&1 If the build works, install everything except the dll (if you can). Then, close down all cygwin programs (including bash windows, inetd, etc.), save your old dll, and copy the new dll to the correct place. Then start up a bash window, or run a cygwin program from the Windows command prompt, and see what happens. If you get the error "shared region is corrupted" it means that two different versions of cygwin1.dll are running on your machine at the same time. Remove all but one. I may have found a bug in Cygwin, how can I debug it (the symbols in gdb look funny)? Debugging symbols are stripped from distibuted Cygwin binaries, so any symbols that you see in gdb are basically meaningless. It is also a good idea to use the latest code in case the bug has been fixed, so we recommend trying the latest snapshot from or building the DLL from GIT. To build a debugging version of the Cygwin DLL, you will need to follow the instructions at . You can also contact the mailing list for pointers (a simple test case that demonstrates the bug is always welcome). How can I compile Cygwin for an unsupported platform (PowerPC, Alpha, ARM, Itanium)? Unfortunately, this will be difficult. Exception handling and signals support semantics and args have been designed for x86 so you would need to write specific support for your platform. We don't know of any other incompatibilities. Please send us patches if you do this work! How can I adjust the heap/stack size of an application? If you need to change the maximum amount of memory available to Cygwin, see . Otherwise, just pass heap/stack linker arguments to gcc. To create foo.exe with a heap size of 200MB and a stack size of 8MB, you would invoke gcc as: gcc -Wl,--heap,200000000,--stack,8000000 -o foo foo.c How can I find out which DLLs are needed by an executable? objdump -p provides this information, but is rather verbose. cygcheck will do this much more concisely, and operates recursively, provided the command is in your path. How do I build a DLL? There's documentation that explains the process in the Cygwin User's Guide here: . How can I set a breakpoint at MainCRTStartup? (Please note: This section has not yet been updated for the latest net release.) Set a breakpoint at *0x401000 in gdb and then run the program in question. How can I debug what's going on? You can debug your application using gdb. Make sure you compile it with the -g flag! If your application calls functions in MS DLLs, gdb will complain about not being able to load debug information for them when you run your program. This is normal since these DLLs don't contain debugging information (and even if they did, that debug info would not be compatible with gdb). Can I use a system trace mechanism instead? Yes. You can use the strace.exe utility to run other cygwin programs with various debug and trace messages enabled. For information on using strace, see the Cygwin User's Guide. Why doesn't gdb handle signals? Unfortunately, there is only minimal signal handling support in gdb currently. Signal handling only works with Windows-type signals. SIGINT may work, SIGFPE may work, SIGSEGV definitely does. You cannot 'stop', 'print' or 'nopass' signals like SIGUSR1 or SIGHUP to the process being debugged. The linker complains that it can't find something. A common error is to put the library on the command line before the thing that needs things from it. This is wrong gcc -lstdc++ hello.cc. This is right gcc hello.cc -lstdc++. Why do I get an error using struct stat64? struct stat64 is not used in Cygwin, just use struct stat. It's 64 bit aware. Can you make DLLs that are linked against libc ? Yes. Where is malloc.h? It exists, but you should rather include stdlib.h instead of malloc.h. stdlib.h is POSIX standard for defining malloc and friends, malloc.h is definitely non-standard. Can I use my own malloc? If you define a function called malloc in your own code, and link with the DLL, the DLL will call your malloc. Needless to say, you will run into serious problems if your malloc is buggy. If you run any programs from the DOS command prompt, rather than from in bash, the DLL will try and expand the wildcards on the command line. This process uses malloc before your main line is started. If you have written your own malloc to need some initialization to occur after main is called, then this will surely break. Moreover, there is an outstanding issue with _malloc_r in newlib. This re-entrant version of malloc will be called directly from within newlib, by-passing your custom version, and is probably incompatible with it. But it may not be possible to replace _malloc_r too, because cygwin1.dll does not export it and Cygwin does not expect your program to replace it. This is really a newlib issue, but we are open to suggestions on how to deal with it. Can I mix objects compiled with msvc++ and gcc? Yes, but only if you are combining C object files. MSVC C++ uses a different mangling scheme than GNU C++, so you will have difficulties combining C++ objects. Can I use the gdb debugger to debug programs built by VC++? No, not for full (high level source language) debugging. The Microsoft compilers generate a different type of debugging symbol information, which gdb does not understand. However, the low-level (assembly-type) symbols generated by Microsoft compilers are coff, which gdb DOES understand. Therefore you should at least be able to see all of your global symbols; you just won't have any information about data types, line numbers, local variables etc. Shell scripts aren't running properly from my makefiles? If your scripts are in the current directory, you must have . (dot) in your $PATH. (It is not normally there by default.) Better yet, add /bin/sh in front of each and every shell script invoked in your Makefiles. What preprocessor macros do I need to know about? gcc for Cygwin defines __CYGWIN__ when building for a Cygwin environment. Microsoft defines the preprocessor symbol _WIN32 in their Windows development environment. In gcc for Cygwin, _WIN32 is only defined when you use the -mwin32 gcc command line options. This is because Cygwin is supposed to be a POSIX emulation environment in the first place and defining _WIN32 confuses some programs which think that they have to make special concessions for a Windows environment which Cygwin handles automatically. Check out the predefined symbols in detail by running, for example $ gcc -dM -E -xc /dev/null >gcc.txt $ gcc -mwin32 -dM -E -xc /dev/null >gcc-mwin32.txt Then use the diff and grep utilities to check what the difference is. How should I port my Unix GUI to Windows? Like other Unix-like platforms, the Cygwin distribtion includes many of the common GUI toolkits, including X11, X Athena widgets, Motif, Tk, GTK+, and Qt. Many programs which rely on these toolkits will work with little, if any, porting work if they are otherwise portable. However, there are a few things to look out for: Some packages written for both Windows and X11 incorrectly treat Cygwin as a Windows platform rather than a Unix variant. Mixing Cygwin's Unix APIs with Windows' GDI is best avoided; rather, remove these assumptions so that Cygwin is treated like other X11 platforms. GTK+ programs which use gtk_builder_connect_signals() or glade_xml_signal_autoconnect() need to be able to dlopen() themselves. In order for this to work, the program must be linked with the -Wl,--export-all-symbols linker flag. This can be added to LDFLAGS manually, or handled automatically with the -export-dynamic libtool flag (requires libtool 2.2.8) or by adding gmodule-export-2.0 to the pkg-config modules used to build the package. Programs which include their own loadable modules (plugins) often must have its modules linked against the symbols in the program. The most portable solution is for such programs to provide all its symbols (except for main()) in a shared library, against which the plugins can be linked. Otherwise, the symbols from the executable itself must be exported. If the package uses the CMake build system, this can be done by adding ENABLE_EXPORTS TRUE to the executable's set_target_properties command, then adding the executable's target name to the target_link_libraries command for the plugins. For other build systems, the following steps are required: The executable must be built before its plugins. Symbols must be exported from the executable with a -Wl,--export-all-symbols,--out-implib,libfoo.exe.a linker flag, where foo represents the name of the executable. The plugins must be linked with a -Wl,/path/to/libfoo.exe.a linker flag.