How do we get from source code to machine code? How does a command like make work?
Common commands
code hello.c # create file
make hello # run the "compiler" to convert to machine code
./hello # execute/run the programcode hello.c- makes a new
.cfile
- makes a new
make hello- creates a file named
hello(no extension) → converts from source to machine code
- creates a file named
./hello- runs the code
- Other commands
more about make
makeis not actually a compiler, but a useful program that automates the process of running an actual compiler for you (clangfor us in this case)- when we’re using
make hello:- make runs
clang, and the output by default isa.out(assembly output) - so if you use
clangdirectly, you don’t get a program calledhellobut you geta.out
- make runs
make hello
ls # hello
./hello
clang hello.c
ls # a.out
./a.outCommand line arguments
Inputs provided to commands at the command line
code hello.c
make hello
./hellomake hello- source to machine code manually
- triggers the compilation
- specifies what program to make
./hello- run the machine code
make to clang
clang -o hello hello.c -lcs40
./hello- arguments
-o hello hello.c-o- output- outputs the default
a.outname tohello
-lcs50- using 3rd party libraries:
lstand for link against a library - When using
clangorgccdirectly, you must specify all needed libraries manually — which can be tedious. - this is why
makeis more convenient, it does all these under the hood
- using 3rd party libraries:
argc and argv
- If we want to use CLI at runtime instead of while the program is running, we can change our
mainmethod to look like this
#include <cs50.h>
#include <stdio.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
printf("hello, %s\n", argv[1]);
}
else
{
printf("hello, world\n");
}
}argc- argument count- stores the number of command line arguments the user typed when the program was executed
./greedy- argc == 1./greedy 100- argc == 2
argv[]- argument vector- array of the characters passed as arguments at the command line
- stores strings
- so even tho you typed ints in the CLI it is a string
- first element is
argv[0]and last isargv[argc-1