This may be a stupid question. How do you use C libraries without an IDE? I want to only use a text editor.
2 Answers
(does this really belong here)?
Example: using the math library. Create this file with your preferred editor:
#include <stdio.h>
#include <math.h> //this declare the math library
int main() {
printf("%f\n", sin(1.0)); // using math and stdio library
return 0;
}
Then you compile:
gcc -o test test.c -lm -lc
Read: compile test.c
to an executable called test
using the libraries libc
and libm
(Notice: you do not need to use explicitly -lc -lm
because they are linked in by default when needed; this is just an example --- other libraries you have to explicitly tell).
Run it:
[romano:~/tmp] % ./test
0.841471
Voilá.
You can get information for the library using section 3 of the man pages; for example
man 3 sin
:
SIN(3) Linux Programmer's Manual SIN(3) NAME sin, sinf, sinl - sine function SYNOPSIS #include <math.h> double sin(double x);
[...]
and so on.
Follow the simple steps:
Open up any text-editor you want to write your program in.
Write a simple program, or any program in C, you want.
Now if you want to add any library in you program, it has the same procedure as it is in an IDE. For example I want to add a library in program named as system library, then I would write:
#include<sys/types.h>
and then write my rest of the program.
- now save the file anywhere you want, with an extension of
.c
. For example: I saved my first file on my desktop, name asHelloWorld.c
.
In terminal, go to the directory where you have saved your file.
Type the following command to create an executable file in the same directory:
gcc –o executable HelloWorld.c
This creates a file named as
executable
in the same directory where the .c file is present.To run the executable file, type the following command:
./executable
and this prints or performs the tasks of your program.
In a nutshell, whatever you use to write the C program, whether its a text editor or an IDE like dev c++, it will work same. IDEs just save your time in writing those commands every time to compile the program.
Happy Coding :)
-l
flag forgcc
/g++
/ld
appropriately.