Generating assembly output from msvc and CMake

Sometimes it’s needed or you may require to see the assembly output listing of a C++ snippet code just for the testing purpose. Testing yourself with Jason Turner’s session might be the example.

If you’re using a msvc with Windows environment, then it’s quite easy by running the simple command line argument:

Let’s say we have an optimizaing.cpp as following:

#include <string>

int main()

{

    std::string s(“a”);

    return s.size();

}

Launch the build environment and run the cl.exe with a ‘/FA’ parameter.


cl /EHsc /nologo /W4  optimizing.cpp /FAs /GL /O2


CMake also automatically adds the target generating assembly output and it’ll be also a good choice when you’re not using msvc.

Let’s say if we have the following CMakeLists.txt,

project(demo)

cmake_minimum_required(VERSION 3.1)

#—————————————————-

# Flags

#—————————————————-

set(CMAKE_CXX_STANDARD 14)

add_definitions(-DCMAKE_EXPORT_COMPILE_COMMANDS=1)

#—————————————————-

# Executable

#—————————————————-

add_executable(optimizing “optimizing.cpp”)


You can generate the build files. I use theMinGWw g++ toolchain here.

cmake -G “MinGW Makefiles” -DCMAKE_BUILD_TYPE=RELEASE ..


Then you’ll see the target.s for the assembly output. For example, the generated Makefile contains ‘optimizing.s’ here.


You’ll finally get the assembly output listing by running make target.s as below:


 

Thanks,

Heejune

Build your own clang example outside of the llvm source tree

Now it’s time to build our own clang standalone tool. The official LibTooling document provides an example code so that I was able to begin with it.

 

How to write CMakeLists.txt for the standalone clang tool?

 

Of course using the cmake is not required, but I wanted to go with it. At first I tried to use the CMakeLists which is included the rtags with few modifications, but it didn’t work well. Instead of digging it further, I tried another CMakeLists found and easily succeeded after adding more libs to link with.

However If you run the cmake, an error will be occurred indicating it failed to find the cmake file for llvm as below output:

 

➜  build$ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..
— The C compiler identification is AppleClang 7.0.2.7000181
— The CXX compiler identification is AppleClang 7.0.2.7000181
— Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
— Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc — works
— Detecting C compiler ABI info
— Detecting C compiler ABI info – done
— Detecting C compile features
— Detecting C compile features – done
— Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
— Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ — works
— Detecting CXX compiler ABI info
— Detecting CXX compiler ABI info – done
— Detecting CXX compile features
— Detecting CXX compile features – done
CMake Error at CMakeLists.txt:26 (find_package):
Could not find a package configuration file provided by “LLVM” with any of
the following names:

LLVMConfig.cmake
llvm-config.cmake

Add the installation prefix of “LLVM” to CMAKE_PREFIX_PATH or set
“LLVM_DIR” to a directory containing one of the above files.  If “LLVM”
provides a separate development package or SDK, be sure it has been
installed.
— Configuring incomplete, errors occurred!
See also “/Users/hekim/Dropbox/clangtool/build/CMakeFiles/CMakeOutput.log”.

 

Screenshot 2016-08-12 08.27.34

 

In such case, you need to define CMAKE_PREFIX_PATH which contains LLVMConfig.cmake for its subdirectory. The files are located at:

➜  build$ find ~/Documents/sources/clang-build -name LLVMConfig.cmake
/Users/hekim/Documents/sources/clang-build/cmake/modules/CMakeFiles/LLVMConfig.cmake
/Users/hekim/Documents/sources/clang-build/lib/cmake/llvm/LLVMConfig.cmake

Screenshot 2016-08-12 08.30.50

 

So, I added the llvm&clang build output root directory(where the Makefile files are generated by cmake),

 

➜  build$ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_PREFIX_PATH=/Users/hekim/Documents/sources/clang-build ..
— Found LLVM 4.0.0svn
— Using LLVMConfig.cmake in: /Users/hekim/Documents/sources/clang-build/lib/cmake/llvm
— User selected librarys = clangFrontend;clangSerialization;clangDriver;clangParse;clangRewriteFrontend;clangStaticAnalyzerFrontend;clangSema;clangAnalysis;clangEdit;clangAST;clangLex;clangBasic;clangTooling
— User selected components = mcparser;bitreader;support;mc;option
—     =
— Configuring done
— Generating done
— Build files have been written to: /Users/hekim/Dropbox/clangtool/build

Screenshot 2016-08-12 08.35.05

➜  build$ make
Scanning dependencies of target example
[ 50%] Building CXX object CMakeFiles/example.dir/main.cpp.o
[100%] Linking CXX executable example
[100%] Built target example
➜  build$ ./example
example: Not enough positional command line arguments specified!
Must specify at least 1 positional argument: See: ./example – help

Screenshot 2016-08-12 08.35.36

Then it succeeded.

Where’s my ‘llvm/tools/clang/example’ binaries?

Recently I got interests in clang & its library(Libtooling, more specifically) so that I decided to start digging in. However, the first frustration came from while building the clang examples.

Download and build the clang source tree

Building the clang executable was easy. The Clang website provides instructions and you’ll get the result by just following it. The clang source code is located as a form of subproject of the llvm. So you need to download the llvm first and clang in order.

  1. Check out LLVM:
  2. Check out Clang:

Then the overall source tree will look like this:

image

The llvm & clang use the CMake, so as a next stage, you’ll need to generate Makefile or any solution files for your favorite build tools with it.

Build LLVM and Clang:

  • mkdir build (in-tree build is not supported)
  • cd build
  • cmake -G "Unix Makefiles" ../llvm
  • make
  • This builds both LLVM and Clang for debug mode.
  • Note: For subsequent Clang development, you can just run make clang.
  • CMake allows you to generate project files for several IDEs: Xcode, Eclipse CDT4, CodeBlocks, Qt-Creator (use the CodeBlocks generator), KDevelop3. For more details see Building LLVM with CMake page.

 

I created a ‘clang-build’ directory instead of ‘build’ with a same level as ‘llvm’ then followed the steps above. You’ll see the llvm & clang executables after finished the whole building process usually takes >= 20 mins.

Where’s the my clang example binaries?

If you look into llvm/tools/clang/examples directory, there’re four examples – AnnotateFunctions, PrintFunctionNames, analyzer-plugin, and clang-interpreter. However, I couldn’t find the executables of those four, later I found out that I should add another flag to build the examples at here(http://stackoverflow.com/questions/6265624/how-to-build-clang-examples-printfunctionnames)

So if you followed the exact steps described above, then no example files are generated:

➜  clang-build$ pwd
/Users/hekim/Documents/sources/clang-build
➜  clang-build$ find . -name ‘PrintFunctionNames*’ -type f
➜  clang-build$

image

The linked Stackoverflow’s post suggests run

make BUILD_EXAMPLES=1

but it didn’t work either with previously generated Makefile. So, I went back to the llvm source directory and had to re-run the following command to generate Makefile again(as the link also suggested).

cmake –DBUILD_EXAMPLES=1 ../llvm

make BUILD_EXAMPLES=1

But it still didn’t succeed. So, lastly, I tried

cmake -DLLVM_BUILD_EXAMPLES=1 -DCLANG_BUILD_EXAMPLES=1 ../llvm

make  (*without* parameter)

Then finally I was able to see the example result.

➜  clang-build find . -name ‘PrintFunctionNames*’ -type f

./lib/PrintFunctionNames.dylib
./tools/clang/examples/PrintFunctionNames/CMakeFiles/PrintFunctionNames.dir/PrintFunctionNames.cpp.o
./tools/clang/examples/PrintFunctionNames/PrintFunctionNames.exports

image

You can also read another CMake options at here: http://llvm.org/releases/3.8.1/docs/CMake.html

Now let’s see how to build your own clang example outside of clang-source tree as next.

Thanks,

Heejune

Demo app shows std::stable_partition and std::rotate works

https://channel9.msdn.com/Events/GoingNative/2013/Cpp-Seasoning

From the beginning of Sean Parent’s great C++ talk, he represented two std algorithms people may not be familiar of. It’s ‘std::stable_partition’ and ‘std::rotate’.

I made a small demo application shows how the two algorithms works. It’s Qt5 based application so that you can freely compile and run from Windows, mac or Linux. Grab the code here: https://github.com/heejune/algorithm-workshop

std::stable_partition example

std::rotate example

Thanks,

Heejune

Running a CCTV Telegram Bot on your Pi

            

Telepot is a python based telegram bot framework which is lightweight, easy to use and supports all of the up-to-date telegram features. For example, I was able to write a small telegram bot running on Pi2 which takes and sends a photo with only few lines using it. Here is how.

1) Although Telepot supports python 2.7 without async feature, I wanted to use Python 3.x. However, the latest Telepot supports async requires Python 3.5 so I had to download and build Python 3.5 on my Pi2. I followed the instruction introduced here https://sowingseasons.com/blog/software/2016/01/building-python-3-4-on-raspberry-pi-2/19864079 except using python source https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tgz

2) Telepot also provides basic samples. You can also find out other API usages through test code. ‘couter/countera’ example is simple but a good start points if you only require receiving telegram message and sending a reply back.

3) Of course you’ll need a Telegram Bot account. There’s a bot named ‘@BotFather’ which does making a bot for you and makes you setting basic info of it. Just initiate a talk to the account and detailed instruction described here: https://core.telegram.org/bots

4) I used the https://github.com/nickoala/telepot/blob/master/examples/chat/countera.py as the starting point. From the source, MessageCounter.on_chat_message will be called responds to the user’s message. If you want to make the CCTV like telegram bot, then just take a picture and send it back within the method.

5) Takes a picture using the picamera module and replies with it. Remove the temporary saved picture after sending it.

6) here is the result: https://gist.github.com/heejune/afd77aeec49e836fa549fc025962ddd8

How to embed the PDFjs into your C# Project

TL;DR

If you needed to add PDF support feature into your C# based project, then using the PDFium & PDFViewer will be the easiest approach. Just include the PDFium via nugget package. You can also find the PdfiumViewer is on the github(https://github.com/pvginkel/PdfiumViewer).

However, the wrapper control only provides basic features so that you might need to consider different solutions in case you required another features such as highlighting text, searching keyword(PdfiumViewer supports the search, but it only returns position information rather actually selecting searched keywords). That’s why I tried to embed the PDFjs into a C# project.

The overall process will be like this:

  1. Include the web browser control into the target project
  2. Download PDFjs and make the C# code locate it.
  3. Navigate the web browser control to the viewer.html which is located at ‘pdfjs-1.4.20-dist/web/viewer.html’
  4. [From C#] Convert the pdf file into base64 string. I did on purpose because the C# application currently I’m writing only handles the PDF as memory buffer. If you could refer to the target PDF as local file, then go with it.
  5. [From viewere.js] Add a helper function which decodes the base64 into an ArrayBuffer and call PDFViewerApplication.open with it.

Code#1. PDF file into base64 and pass it to webbrowser control

Code#2. Open PDFjs with viewer.js and base64 string

The complete example is https://github.com/heejune/WinForm-PDFjs

Got hints following:

http://stackoverflow.com/questions/21797299/convert-base64-string-to-arraybuffer

http://stackoverflow.com/questions/8219694/how-can-i-show-an-image-in-webbrowser-control-directly-from-memory

Emacs orgmode에서 한글 tex, pdf 출력하기

The title of this post is ‘How to export an orgmode doc which contains Korean characters into Tex and PDF’. Assumed only Koreans would read this.

Emacs는 현재 24.5.1 버전을 mac, windows. linux에서 사용하고 있습니다. 주로 mac platform에서 사용하고 있는데, 최근 우리말로 작성한 orgmode article을 tex과 pdf로 export하려 했지만 에러가 나거나 한글이 나오지 않는 현상을 확인하였습니다.

  1. Mac & emacs 환경에서 출력했을 때(실패담)

http://freizl.github.io/posts/2012-04-06-export-orgmode-file-in-Chinese.html 페이지를 참고하였습니다. 페이지에서 안내하는 첫번째 솔루션인,

#+LaTeX_HEADER: \usepackage{CJK}

#+LaTeX_HEADER: \begin{CJK}{UTF8}{gbsn}

#+LaTex: \end{CJK}

했을 때, 에러는 나지 않지만, 한글이 전부 빠진 영문 결과만 출력이 되었습니다. 참고로, 기존에 맥에서는 https://tug.org/mactex/mactex-download.html MacTex 2015 버전을 설치하여 사용하고 있었습니다. 그래서 다시 위의 글 링크를 참조하여 XeLaTex에서 시도하였습니다. 인터넷을 찾아보아도, XeLaTex에서 UTF8 캐릭터들을 잘 출력한다는 글들이 많았습니다. XeLaTex를 사용하기 위해서는 org-latex-to-pdf-process를 새롭게 정의해 주어야 합니다. 다행스럽게도, 위 링크에 함께 잘 나와 있습니다. 기존 org setup 코드에서 아래 lisp 코드를 추가합니다.

그런데, 에러가 납니다. 저의 경우에는 wrapfig.sty가 빠져 있어서 발생하는 에러였는데 쉽게 고칠 수 있을 것 같지 않았습니다. 그래서 ubuntu에서 다시 해보기로 합니다.

  1. Ubuntu에서 Emacs orgmode article을 tex, pdf로 출력하기

Linux에서 설치는 다음 링크를 참고하였습니다.

http://wiki.ktug.org/wiki/wiki.php/%EC%84%A4%EC%B9%98%ED%95%98%EA%B8%B0Linux/tlinstall?action=show

$ wget http://mirror.ctan.org/tex-archive/systems/texlive/tlnet/install-tl-unx.tar.gz
$ tar zxvf install-tl-unx.tar.gz
$ ./install-tl

설치는 full로 하였지만, 여전히 오류가 나더군요. 그래서 이번에는

sudo apt-get install texlive-xetex

추가 패키지 설치를 한 후에,

#+LATEX_HEADER: \usepackage{kotex}

이렇게 kotex 패키지를 orgmode 문서 앞에 명시를 해 주자, 이제야 성공적으로 한글 Tex, PDF 문서를 뽑아낼 수 있었습니다. texlive-xetex 추가 패키지 설치(apt-get) 없이, kotex 패키지 명시만으로 될 수 있을지는 확인해 보지 못했습니다.

참고: http://tex.stackexchange.com/questions/17143/how-do-i-get-korean-hangul-characters-to-typeset-in-latex

도움이 되길 바랍니다.