Reputation: 2142
I have been trying to figure out how to create a C program that can be compiled for all of the major operating systems. I have considered using makefiles so I would just have to change the target OS, but I have a few problems. My first problem is that I cannot figure out how to change the target OS so I can compile on one OS but use the application on all OS's. My second issue is that I cannot figure out how to make it automatically compile all .c files in the src directory, so I do not have to modify the makefile every time I add a new file. Does anybody know how to do this stuff?
My current makefile (currently unmodified from here)
CC=gcc
CFLAGS=-c -Wall
LDFLAGS=
SOURCES=main.cpp hello.cpp factorial.cpp
OBJECTS=$(SOURCES:.cpp=.o)
EXECUTABLE=hello
all: $(SOURCES) $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CC) $(LDFLAGS) $(OBJECTS) -o $@
.cpp.o:
$(CC) $(CFLAGS) $< -o $@q2
Upvotes: 6
Views: 3343
Reputation: 374
The GNU Autoconf is a good place to start. I can't give you a complete answer because I don't know what you'd do for Windows except maintain a set of nmake scripts. While there's a learning curve they make it possible to write make files and c-code that work across platforms. It will not only handle multiple source files for you but help you define target such as 'all', 'install,' 'clean,' etc. If you're familiar with downloading a project and then typing './configure' and then 'make install' then you've probably been a user of an Autoconf generated project.
There are other reasons to use Autoconf than just handling multiple source files.
What makes C/C++ development across flavors of Unix difficult is the definition of 'Unix' and C. Different flavors of Unix have slightly different library or system calls depending on what flavor of standards they support. The same is true of C. So, when writing code you'll see #defines specifying a group of preprocessor symbols that define a version of Unix and C that you'd like to use. Going from GCC to HP C or some other vendor's C compiler may include different 'default' levels of behavior, so you need to make the expected behavior explicit.
Second, you need to define what libraries are required. In your build you might need to probe for mysql libraries and decide what to do if those libraries are not installed. In some cases you might need to not build at all or in some cases you might just substitute for another library (like libdb). Having tried writing complex makefiles to support even two operating systems (Solaris and Linux), I would not want to re-invent this wheel.
Upvotes: 6