compile C program in multiple folders - c

I have a bunch of directories with C programs. I need to compile them one by one and use the result in the main Program.
So my Main program traverse in the Directory structure [I am not sure what the structure is, It may change over time] and compiles one C program at a time, use that result in some computation.
So If I write the main program in C and use nftw to traverse.
OR
Write a Shell main program.
Which appraoch is better?

I guess you use a compatible Unix/Linux/Cygwin system....
Therefore, I would advice to use a shell solution because it is more suitable for directory processing.
Makefile for each program
As #Dogbert said make can be used to build several programs. Build can be performed in parallel (using the option -j). Moreover make can also take care about the dependencies.
I do not know if you are used with Makefile syntax. Therefore I give a quick example about a program requiring three C files and one header file:
program: file1.o file2.o file3.o
gcc -o -o $# $^
%.o: %.c header.h
gcc -c -o $# $<
The following command will compile file1.c, file2.c and file3.c in parallel. Then link stage will wait for the completion of these tree compilations.
make -j3
Directory discovery
The following command finds each Makefile and runs the make command:
find . -name Makefile -exec make -j3 -f '{}' ';' 2>&1 | tee result.txt
If you have 8 cores in your computer, you can use -j8.
Reuse in your main program
The build result is displayed on the shell screen and is also stored in the result.txt file.
More information?
I do not know what is your system, or your knowledge. Hope this can help. If you are not sure to understand some parts, please ask for more information. ;-)

Related

Running c program from command line in one step?

I just got started writing some C programs.
To start with I was just running them through VS code. Nice and easy, I just had to press a button and bam, there it was.
But now I need to pass files as arguments to my program, which creates the need of running it from the command line.
The way I do it now, is using this two step process, (which I think is just the basic way of doing it):
ask#Garsy:~/Notes/ethHack/crpytifiles$ gcc test.c -o test
and then running the file:
ask#Garsy:~/Notes/ethHack/crpytifiles$ ./test
This is a bit tedious in the long run. Is there any way I could do this process in one step?
And perhaps also without creating the executable?
It would be really cool if I could just run it as you normally would with a python or java file, one command, and the thing runs.
You could do that with a makefile. More about GNU Make here.
all:
gcc test.c -o test
./test
The file should be called Makefile or makefile (it can have different names,just keeping it simple), and you can run it by executing:
make
Assuming you have GNU Make installed and test.c is located in the same directory with makefile.
This is a bit tedious in the long run. Is there any way I could do this process in one step?
Yes. You could create a shell function (or an alias if your shell supports alias arguments, which bash does not), e.g.:
ccr() { gcc "$1" -o x.$$ && ./x.$$; rm -f x.$$ }
$ ccr hello.c
Hello, world!
$
which will compile the script, run it if compilation succeeded, then remove the compiled binary.
And perhaps also without creating the execuable?
No (well, not easily). Executing binaries is offloaded to the exec*() function family, and the operations performed are complex and, I suspect, incompatible with stdin operations. So you cannot send the executable to a pipe and execute it from the pipe.
What you can do is use a C interpreter, albeit it is not exactly the same thing.
I am wondering that nobody is issuing the general comparison between an IDE and shell. So yes IDE may give you some comfort. But you will be happy if you learnt the fundamentals of linking & Co from scratch - otherwise the configuration of the
IDE can get pretty challenging, when you start stuff that does not work out of the box.
The rest are helpful tips to increase the efficiency on the shell - like make or
other automation builders. Shell editors provide additional tools and plugins to increase your workflow - eg with vim as an shell editor (and some plugins) you come pretty close to an IDE. This includes syntax highlight,
code check, compile and run of the program, etc... just my 2 cents
As #alex01011 correctly stated, what you need is a Makefile, and his solution should work. What I want to suggest here is a better Makefile.
First make already know how to use build test from test.c in the simple case. It will add parameters to the preprocessor, compilation and linker steps from Makefile variables, so it is better to use the built-in command for better fleksibility.
# Tell make that `all` and `run` is technically not files that will be built
.PHONY : all run
# These flags are passed to the compiler, we always want to compile with
# warnings when developing
CFLAGS= -Wall
# `all` is the first rule, so that is the one that will be build not
# specifying anything on the command line
# `all` also depends on `test` so that will be built from `test.c` calling
# `make` or `make all`
all: test
# `make run` will run your command. `run` depends on `all` to make sure the
# program exist before calling `./test`
# Note the the indent must be made with a tab and not spaces
run: all
./test
If your program is composed of more files, things get a lit more complicated, but still easily manageable:
# Example of a Makefile for a project that is composed of the files
# test.c foo.c, bar.c, foo.h and bar.h
# The main-function is in test.c, and the generated program will be
# called `test`
#
.PHONY: all run
CFLAGS= -Wall
all: test
# foo.c includes foo.h therefore foo.o depends on foo.h in addition to foo.c
foo.o: foo.h
# bar.c includes bar.h therefore foo.o depends on bar.h in addition to bar.c
bar.o: bar.h
# test.c includes both foo.h and bar.h
test.o: foo.h bar.h
# test should be linked with foo.o and bar.o in addition to test.o
test: foo.o bar.o
run: all
./test
Now typing make run will automatically build and link test, if needed, and the run ./test if there was no errors.
Other variables you may set in addition to CFLAGS are CC, CPPFLAGS, LDFLAGS, LOADLIBES and LDLIBS.
Often you also want to have a clean targets in your Makefile for typing make clean to remove generated files. See info make for more details.

How to produce a makefile that runs multiple programs after each other in c?

I have written two programs. The first one, ProgramOne, creates inputfiles for the second program, ProgramTwo (The two programs have no files in common, the output written by ProgramOne is just the input of ProgramTwo). Sometimes running the first program takes some time, but on other times it takes just a few seconds, depending on the dimensions I am simulating at.
I would therefore like to put all my files into one folder and create a makefile that is able to make commands to run:
ProgramOne
ProgramTwo
The two programs right after each other
The first two are not that difficult to write, the third one is the problem however (So at the moment I am able to run ProgramOne, then run ProgramTwo, which takes me two commands in the terminal, but I would like to make this one command as well in some cases). How do I make clear to the compiler that I want the two programs executed after each other.
At the moment I have a fairly standard makefile, but I have written the following:
(note that programone.c contains a main function, and only a main-function, depending on nothing from SRCS (the files for ProgramTwo))
(Another important note: to run ProgramTwo, I need to specify some arguments. In the terminal I would write: ./RunProgramTwo -v results. How do I need to specify these arguments whenever I would like to run the two programs after each other?)
(I also left some things out, like a clean and distclean command, but I do not think they are relevant to this case. If you think so however, I will provide my complete makefile upon request)
NVCC = nvcc
NVCFLAGS = -arch=sm_30
CFLAGS = -Wall -pedantic -g
LDLIBS = -lz -lpthread
SRCS := allfiles.c
OBJS := allfiles.o
all: .depend RunProgramOne RunProgramTwo RunAll
RunProgramOne: $ programone.o
${NVCC} ${NVCFLAGS} ${LDLIBS} $^ -o $#
RunProgramTwo: ${OBJS} main.o
${NVCC} ${NVCFLAGS} ${LDLIBS} $^ -o $#
RunAll: RunProgramOne RunProgramTwo
depend:
${NVCC} -M ${SRCS} > .depend
.depend: ${SRCS} makefile
${NVCC} -M ${SRCS} > .depend
This does not seem to do the job as I just get ProgramTwo running when I invoke ./RunAll.
Note that I am currently thinking of a solution where my two programs are decoupled from each other. I am also able to make the main-function in ProgramOne into a function, which I then invoke at the very beginning of the main-function of ProgramTwo. In this way, I can easily generate a makefile command for the third of my options, namely the RunAll, but then I do not know how I can achieve the first two.
I would prefer a solution such that my two programs are decoupled, but if this is not possible, feel free to tell me any possible way I can make this work.
I already looked up basic information about makefiles (simple tutorials) and looked at the manual for makefile itself, but I do not seem to find a solution.
Any help is greatly appreciated.
This target doesn't run anything: it just declares prerequisites but you have no recipe (the recipe is the thing that's passed to the shell and executed):
RunAll: RunProgramOne RunProgramTwo
If you want this target to run the programs you have to write a recipe that does this:
RunAll: RunProgramOne RunProgramTwo
./RunProgramOne
./RunProgramTwo

How to write a Makefile to compile a simple C program

Compile the following program
#include <stdio.h>
int main(void)
{
printf ("Hello from your first program!\n");
return 0;
}
a)-by using file of type Makefile
b)-the executable will be named Hello
"Please help to do an exercise. I know how to do it in CodeBlocks, but I don't know what Makefile is and how to write it in Linux. I compiled it using command "gcc filename.c" and subsequently "./a.out" but I still don't understand what the Makefile is. Is it a sort of shell script, an instruction? How would a Makefile for this task exactly look? Thanks in advance :) "
This is your simple make file for hello program.
CC = gcc
CFLAGS = -g
RM = rm -f
default: all
all: Hello
Hello: Hello.c
$(CC) $(CFLAGS) -o Hello Hello.c
clean veryclean:
$(RM) Hello
Suppose you have two makefiles in one directory named makefile.m1 and makefile.m2 and if you want build both make file then please use following commands
make -f makefile.m1
make -f makefile.m2
or use single Makefile that contains:
m1:
make -f makefile.m1
m2:
make -f makefile.m2
and use make m1 or make m2
Now lets clear your doubt about name of make file must not require Makefile
You can name makefile whatever you want. suppose i would like to give name myfirstmakefile.mk. To use it later you need to tell make what makefile you want. Use -f option for this:
make -f myfirstmakefile.mk
And again extantion .mk is also not manadatory you can use whatever you want but never forgot to use -f option.
so may this help make sense to you.
A makefile is a recipe for the make utility how to create some file (called a target) from some other files (called dependencies) using a set of commands run by the shell. A makefile typically looks like this:
target: dependency [...]
command1
command2
Try running man make for details.
Now for your task, really there is no need for a Makefile, since make has built-in rules that know how to compile a simple program. All you need to do is place your C source in a file named after the executable name (Hello) and with a .c extension, i.e. Hello.c.
Then a simple
$ make Hello
cc Hello.c -o Hello
does everything. If you want to use gcc instead of cc, you can run
$ rm Hello
$ make CC=gcc Hello
gcc Hello.c -o Hello
If you tell your instructor/teacher/prof that an empty makefile is all you need since you know the built-in rules do the right thing, you'll get some extra credit and maybe your instructor has learnt something new :-) If you are asked for a reference, you could quote the relevant parts of the make manual, or, do it like a pro, quote from the POSIX Standard for the make utility, section Default Rules.
before going for makefile you have to know what's it and why we need it
What is Makefile?
Makefile is a script written in a certain prescribed syntax which helps to build the target output (normally, one or more executables) from source files by compilation and linking. In simple words, makefile will compile your source code in simple & fast way.
Why we need Makefile?
=> Large projects can contain multiple source files which are dependent in one another or arranged in hierarchical manner for example, in order to compile file A, you have to first compile B; in order to compile B, you have to first compile C; and so on.
=> Make is a solution to these problems. It can be used to compile whole project in well arranged manner and generate your target according to your make rule(which we will discuss later) by entering single command that is make.
=> An important feature is that when a project is recompiled after a few changes, it will recompile only those files which are changed, and any other files that are dependent on it. This saves a lot of time.
=> For a large project, when a few changes are made to the source, manually recompiling the entire project each time is tedious, error-prone and time-consuming.
Here is nice link for it :How to write first makefile
A makefile is a recipe for computers with instructions how to perform certain tasks and with dependencies between those tasks.
In the simple form, it looks like so:
a.out: filename.c
gcc filename.c
Read: "To build a.out from filename.c, run the command gcc filename.c. If a.out is newer than filename.c, then don't do anything"
Note: The first character in the gcc line must be a tab.

multiple small programs in one code::blocks project

I am new to Code::Blocks. For my studies I am programming several small programms in C (just to try things out).
I tried to put them all in one project, because they belong to the same topic, but that doesn't work because each of them has a main function.
Any ideas how I can put those files together somehow, but not depending on each other?
Suppose your source files are called
prog1.c
prog2.c
mylib.c
mylib.h
where prog1.c and prog2.c each contain a main() function and mylib.c (with the corresponding header file mylib.h) contains some library functions that should be linked to each program. In your Code::Blocks project you need to create multiple targets now. From the menu choose 'File/New/Build target...' and name them 'prog1' and 'prog2'. Now add all of your source files to the project (in case you haven't done so already).
Now right-click on prog1.c and select "Properties..." from the context menu. In the dialog box choose the 'Build' tab and make sure that under "Belongs to target" only "prog1" is checked. Do the same with prog2.c and the target "prog2". For "mylib.c" make sure that both "prog1" and "prog2" are checked.
Now you can easily choose in the UI which build target to build and run. Note that if you add another target, say "prog3", then you have to go to the build properties of prog1.c and prog2.c again and uncheck "prog3".
A C program should contain only one main function.. Divide all your separate programs as Functions and put them in a single C program or you can even put it in multiple files and compile them..
You can use a switch case for calling different functions..
Remove the main function from all the programs and convert them into functions..
Call them where ever required.. This will help you..
let's say that your project contains 3 c files and each c file is a separate program and it contains its own main function:
program1.c
program2.c
program3.c
So you can write a Makefile (its name in your computer should be "Makfile"). It will build the program you want separately
This is how your makefile looks:
all: program1 program2 program3
%.o: %.c
$(CC) $(CFLAGS) -c -o $# $^
program1: program1.o
$(CC) $(LDFLAGS) -o $# $^
program2: program2.o
$(CC) $(LDFLAGS) -o $# $^
program3: program3.o
$(CC) $(LDFLAGS) -o $# $^
clean:
rm -f *.o program1 program2 program3
with the above Makefile you can build each program separetly
example
$ make program1
will build only program1
or you can buil all programs with
$make all
It seems to me as if you are starting to build some nice utility functions. So follow the advice offered by raghu-srikanth-reddyce and create separate functions for each little program. However I would add that it would be better to create yourself a simple C library to keep them all in which you can link to at any time. Most professional programmers keep such libraries.
A simple makefile will enable you to build a final binary that you can link to.
Good luck with your programming ;)
If you want to compile in one file, you dont need a Project File then.
Just make a New File, then write all the code in a single file. Also use Function and Procedure if you need it.
This is quite late but since I was once here with the same question, and I believe most students had/ have/ will have this same question, let me elaborate where you have been played at.
In Educational Courses and in Real World, a project is (in general) some problem you work on, find a solution, then make a report (+ documentation) on it.
In Programming IDE, a project is the problem's solution itself. Hence, while you may have multiple individual problems within one project in any Python IDE, Any standard C/C++ IDE project must have only one 'main()' to rule them all (unless you know how to create makefiles).
What the AP tried to do is to put several different problem's solutions fit within one solution's space - not a possible thing to do in Code::Blocks. Even if all the problems may share the same topic (say, Graph Theory), they are individual problem (Dijkstra vs Floyd) themselves.

How to Compile a C program in C?

I am making a program in c that can produce another c code.
How to, using the first program, compile and run the second program immediately after the second program has been produced?
One way is to used system() call ...
system("cl generated_file.c -o gen_exe") ;
system("./gen.exe");
or
system("gcc generated_file.c -o gen.exe");
system("./gen.exe");
Or you use a simle batch or script or makefile to do this
I'll make two notes in one:
First, if you have one program that generates source code, why not use the normal build system to handle this for you? For a Make-based build system it could look something like this:
second_program : second.c
$(CC) $(CFLAGS) -o $# $<
second.c : first_program
./first_program $(GENERATION_OPTIONS) > $#
first_program : $(LIST_OF_SOURCE_FILES)
$(CC) $(CFLAGS) -o $# $<
This would be more in line with the Unix philosophy than having the first program run an external command, which is always nice.
Second, do you want the second program to be generated and executed dynamically? I.e. will the resulting code depend on some dynamic state of the first program, and could the output from the second program be relevant to the first?
If so, perhaps you should take a look at what you can do with a library to run some script language like LUA or ECMAScript.
(This is perhaps a bit too advanced for the case you are asking about, but it's always nice to know what options there are.)
You'd need to embed a compiler into your app(such as libtcc or lcc) or invoke one via a command line, but that requires detecting what the user has installed or at the very least including extra binaries with your app

Resources