How can I compile, assemble and link a C++ file using Clang? - c++

I have been coding for over 5 years and would now like to take a step away from IDE's and try a project without one. I have the things I need to get started (I think), a HelloWorld.cpp file, the Windows Command Prompt open and Clang installed.
Now that I have these things my question is this - What do I need to type into the Command Prompt to make Clang take my C++ code in the HelloWorld.cpp file and compile it into a separate file containing the assembly code, and then make Clang take my assembly code and assemble it into a separate file containing the object code, and then finally make Clang take my object code and link it into a separate file containing the machine code?
Ultimately meaning at the end I will have 4 files, one with C++ code, one with assembly code, one with object code and finally one with machine code. The point of all of this being the ability to read and understand each stage of the process before running the file containing the machine code.
Being someone who has left the world of IDE's for the first time, I find the official Clang documentation very confusing and cannot find a straight answer to my question.

Same as with GCC, and I'll do you one better by first preprocessing the source file. In principle Clang also can emit LLVM bitcode or LLVM IR as two extra intermediate stages.
clang++ source.cpp -E
clang++ source.ii -S
clang++ source.s -c
clang++ source.o
This last one gives a.out as an executable file. You can define the output file for each command by appending
-o output.file
The extensions may not be 100% correct. Just check what comes out.

Related

Whenever I try to update my code in C++(VSCode) with the g++ thing, it doesn't update what I put even after deleting the old .exe file

my code looks like ^^^ (comments because i make a file for notes on a new programming language im learning to look back at to help me)
I will put g++ filename.cpp and then ./a.exe after making a change and it doesn't change the output in the terminal. So for example if I put a :) at the end of the last string, it wouldn't update what it puts in the terminal even after doing g++ filename.cpp. I've tried deleting the older a.exe file before doing g++ but it doesn't fix the problem.
Please make sure you are actually using the GCC Compiler and that you are not getting errors at the moment of compile your code. You can use this to check the compiler: g++ --version; if you don't have the compiler installed, it will give you an error.
Also, at the moment of compile your code, you should use the g++ installed on your computer with the .cpp file that you want to compile and create the .exe file.
Example:
Here we have Basic00.cpp having a simple "hello world":
Then, we run g++ .\Basic00.cpp
It will create the a.exe file:
Now you just need to run .\a.exe:
And, if you want to add ":)" at the end of the string, you just need to add it, compile the code again (step 2) and run the exe file (step 4):
I recommend that you read this about how to use VS Code with G++ to compile and run your code without having issues. Very important: Remember that you need to compile your code every time that you make a change.
Edit with the new Image: I checked your image and the tab is showing a white circle, it means that you are not saving the changes, press Ctrl+S (to save) or configure Auto Save on File -> Auto Save, after saving compile your code again and run the .exe file.

How do I compile a C++ file to WebAssembly?

Suppose I have a simple, self-contained C++ file (math.cpp) like this:
int add(int x, int y) {
return x + y;
}
How would I compile it to WebAssembly (math.wasm)?
Note: I am using the Clang tool-chain.
I found this gist to be very helpful.
Basically, this are the steps:
(build llvm and clang 5.0.0 or above with -DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=WebAssembly)
Compile the .cpp soure to llvm bitcode with clang:
clang -emit-llvm --target=wasm32 -Oz math.cpp -c -o math.bc
Compile the bitcode to s-assembly:
llc -asm-verbose=false -o math.s math.bc
Use binaryen's s2wasm tool to create a .wast file
s2wasm math.s > math.wast
Use WABT's wast2wasm tool to translate the textual .wast file into binary .wasm:
wast2wasm -o math.wasm math.wast
Some of the steps feel redundant but I have not yet found a tool that allows shortcuts. (It would be nice if llc could compile directly to .wasm, or if s2wasm actually created binary .wasm files as the name suggests.) Anyway, once you got the toolchain running it's relatively painless. Note, however, that there are no C or C++ standard libraries for web assembly yet.
Alternatively, if you need the .wasm file just for trying out stuff you can get away without all the toolchain trouble. Browse to https://mbebenita.github.io/WasmExplorer/, paste in your C/C++ code, and download the compiled .wasm file.
Thank you #noontz and #LB-- for pointing out that
Actually as the comments in the gist suggest you can skip binaryen and compile straight to wasm from Clang/LLVM. I'm currently using the following command line for C++ :
clang++ test.cpp -ObjC++ --compile --target=wasm32-unknown-unknown-wasm \
--optimize=3 --output test.wasm
Emscripten comes with everything you will need to compile a C++ file to wasm. Emscripten also has an SDK that makes life easy when it comes to installing all the necessary tools.
By default, however, Emscripten will add some framework code to your wasm file as well as generate some html and javascript.
It is possible to create a minimal wasm file with Emscripten that doesn't include any framework code, javascript, or html. Using options -s SIDE_MODULE=1 -Oz -s ONLY_MY_CODE=1 while compiling with emcc or em++ will give you a minimal wasm file.
The following command would export a minimal wasm file using your examples and Emscripten:
em++ math.cpp -o math.wasm -Oz -s SIDE_MODULE=1 -s WASM=1 -s "EXPORTED_FUNCTIONS=['_add']" -s ONLY_MY_CODE=1
As of 2019, Clang (8) supports webassembly out of the box. Here is a repository that contains everything needed to compile, link and run a simple .wasm file.
https://github.com/PetterS/clang-wasm
Currently the easiest way to compile C and C++ is with emscripten. The components you mention are all components, but emscripten is a full toolchain that supports building end-to-end, and includes all the parts you need including libc/libc++, and a variety of other useful libraries. It supports targeting both asm.js and wasm.
Based on the answers in this thread, I've created a little guide.
For me, the easiest way was to compile emscripten (the website is also a great starting point!) on my machine, compile the code to wasm, generate the appropriate bindings and hide all this in a wrapper on the JS-Side to that I get a nice interface.
Because of the name mangling of c++, I've found getting started with C is easier.
A little late for this answer but there are beautiful tools online for compiling your scripts.
By example, I'm using this one. That one giving you minimim option of compiling (C,C++,std99...) but there are sufficient : https://wasdk.github.io/WasmFiddle/
And depending of how you gonna use it, you can choose between differents languages such as x86, code Buffer. You can also share your code, kind of functions that I find cool when you are working with some other buddy : https://wasdk.github.io/WasmFiddle/?gus9d :)

md5sum value changes every time I compile cuda source code

I was trying to verify if my macro really works during compilation by md5sum command in ubuntu.
For example, by "nvcc -DTEST_MACRO ...." I got an executable A.
Then by "nvcc ..." I got an executable B.
Of course the md5 values are different.
But, I recompiled and generated A again. Its md5 is different from previous one.
I took a pure c++ code and checked with g++, and its md5 value turns out to be the same no matter how many times I compiled. So I think there is something like time stamp in the executable generated by nvcc.
Just out of curiosity, how do I verify if my thought is right?
Anyway, how do I verify if "TEST_MACRO" really works in this case?
I think this variability is not necessarily due to an embedded timestamp, but rather by the way nvcc builds executables.
nvcc is a compiler-driver, meaning it launches a sequence of commands "under the hood" to compile code. During the execution of this sequence, a variety of temporary files are created with randomly-generated filenames. You can get a sense of this by looking at the output of your nvcc compile command with the -v switch added.
Some of these filenames do get embedded in the executable, and since these randomly-generated file names vary from one invocation of the nvcc compile command to the next, the resultant binary will vary.
If you want to verify this yourself, run your nvcc command with -v added. Then inspect the output at the end for a tmpxft... filename. Then grep the generated executable for that filename, eg.:
grep tmpxft_0000a76e myexe
(replace the tmpxft_0000a76e with whatever appears in your nvcc verbose output, and replace myexe with the actual name of your executable.)
If you want to verify if a TEST_MACRO really works, there are a few options. The least intrusive might be to put the following line in your TEST_MACRO body:
#ifdef TEST_MACRO
...
#warning TEST_MACRO_COMPILED
...
#endif
and you should see this echo'ed to the output during compilation, when you specify -DTEST_MACRO
(The above is a useful technique to avoid mistakenly including debug macros and other things you don't want in a production/release build of code.)
Of course, there are probably many other possibilities. If the test macro includes executable code, you could put a printf statement in it, to see evidence at run-time.

How to generate LLVM bitcode for a file using a compilation database?

I want to generate LLVM bitcode for a large number of C source files for which I have a compilation database . Is there way to invoke clang such that it reads the compilation database and uses the appropriate flags?
Background
For toy programs, the command to generate LLVM bitcode is simple:
clang -emit-llvm -c foo.c -o foo.bc
However, source files in large projects require lots of additional compilation flags, including -Is and -Ds and whatnot.
I want to write a script that iterates over a large number of source files and calls clang -emit-llvm ... on each to generate LLVM bitcode. The difficulty is that each clang -emit-llvm ... command has to have the flags specific to that source file. I have a compilation database for these source files, which perfectly captures the flags needed for each individual source file. Is there a way to make clang -emit-llvm ... aware of my compilation database?
One solution I've thought of is to parse the compilation database myself and find the appropriate entry for each source file, and modify the command entry to (a) include -emit-llvm and (b) change -o foo.o to -o foo.bc, and then run the command. This might work, but seems a bit hacky.
Instead of parsing the compilation database yourself, you could rely on the Python binding to do so. Judging from the test suite of the binding, you could do something like:
cdb = CompilationDatabase.fromDirectory(kInputsDir)
cmds = cdb.getAllCompileCommands()
and then slightly update the content of cmds.

Get the compiler options from the program [duplicate]

This question already has answers here:
Detect GCC compile-time flags of a binary
(4 answers)
Closed 9 years ago.
Is there any macro in c++ (using gcc) to get the compilation options used to build the executable ?
I'm sure I saw something like that in some about dialogs.
any help will be appreciated
PS: while the question in Detect GCC compile-time flags of a binary interests in finding the options activated to compile a program, I'm interesting in finding the exact command line options used to compile my program from within this program source.
Apart from creating the compile string from the
Common Predefined Macros
, which seems hectic. I think there is an easy way to do it. The gcc -V on debian gives back flags used for configuration.
However, my shot would be to get full command in ./configure equivalent step and dump it to some file like config_line.h as a define.
Something like:
./configure:
#!/bin/sh
echo "#define conf_flags \"configured with: "$*"\"" >> config_line.h
#do some configuration steps here
#maybe even compilation itself
Then:
luk32:~/projects/tests$ ./test.sh --with=test
luk32:~/projects/tests$ cat ./config_line.h
#define conf_flags "configured with: --with=test"
You get full config line defined in the external file under a define statement. I think its fairly straight forward and easy to use. And no need for much compiler magic.
It is also worth of noting you can most probably (if not always) create such file(s) right before the actual compilation so they are actually up-to-date and valid during compilation step. Answer in get-the-compiler-options-from-a-compiled-executable would imply the executable already exists, which might be a bummer in some cases.
Note: I gave bash example, but I'm pretty sure you can output similar header file under any half-descent build system, be it make, qmake, cmake, etc. the bash begin the simplest case.
I think most of them have access to the command line they are invoked with, as well as they provide easy way to get actual compile command. For example to provide two literals, one with commands used for make like -j 13 and another g++ ... used for actual compilation step performed by make.
Note2: I know this is not an answer the OP asked, but I guess it serves his purpose in the 1st place.
Because I'm using qmake build system I came across this solution :
I added this line to the end of my pro file :
QMAKE_CXXFLAGS += -DFLAGS=\"$$QMAKE_CXXFLAGS $$QMAKE_CXXFLAGS_RELEASE\"
then retrieved what I want from the FLAGS macro