What is the difference between make and clang?
Clang
$ clang -o hello hello.c
Clang is a compiler tool that facilitates the compilation of source code into an executable binary file.
Make
$ make hello
make is a build automation tool that helps in compiling and building software projects by automating the process of building executable programs and libraries from your source code.
Both Clang
and Make
are equipped with the ability to compile source code into an executable binary file. However, Make offers additional functionality in the background, allowing users to avoid concerning themselves with intricate details.
What happens during the compilation process?
Step
-
Preprocessing
-
Compiling
-
Assembling
-
Linking
Example
#include <cs50.h>
#include <stdio.h>
int main(void) {
string name = get_string("What's your name?");
printf("hello, %s\n", name);
}
Preprocessing
string get_string(string prompt);
int printf(string format, ...);
int main(void) {
string name = get_string("What's your name?");
printf("hello, %s\n", name);
}
Put simply, during the preprocessing step, the compiler will duplicate the contents of specified files, such as cs50.h
and stdio.h
, and merge them with your source code.
Compiling
// Example
...
main:
.cfi_startproc
# BB#0:
pushq. %rbp
// some other assembly code....
Compile your source code into assembly code.
Assembling
0111111011101001000001001
0100100101010000000111000
1111111111111000001010010
...
Convert your assembly code into machine code.
Linking
Combine your machine code with any external libraries utilized in your project. During this step, your code will be linked with cs50.c
and stdio.c
.
How array stored in memory?
Imagine that memory is a large shelf, with each slot representing one byte. When we declare a variable, we store some data in it. For instance, when declaring an integer, it will require 4 bytes of memory.
How about array?
int main(void){
int scores[2];
}
When declaring an array, a contiguous block of memory is created.
How c represent string in memory?
In C, a string can be considered as a character array. However, an additional character '\0'
is appended at the end of the array, which serves as a terminating signal.
#include <stdio.h>
int main() {
char message[] = "1234567890";
if (message[10] == '\0') {
printf("nil\n");
}else {
printf("%c\n", message[10]);
}
}
// shows nil
Command-line argument
command linearguments just let you express your whole thought all at once (View Source)
Example:
GitHub - piuccio/cowsay: cowsay is a configurable talking cow
$ cowsay moo
$ cowsay -f duck quack // change to duck and say quack
Naming is a critical aspect of programming. Effective naming practices can significantly enhance an application’s expressiveness.
cowsay
is a good example of naming. When we use this command line tool, we can get a rough idea of what the tool can do.