Crosscompile for Window on Ubuntu MinGW CMake

In this article, I will describe the process of building libraries and applications for Windows using the MinGW32 toolchain on Ubuntu.
Install wine, mingw:


sudo apt-get install wine mingw-w64

After that, you can already build C / C ++ applications for Windows:


# C
i686-w64-mingw32-gcc helloWorld.c -o helloWorld32.exe      # 32-bit
x86_64-w64-mingw32-gcc helloWorld.c -o helloWorld64.exe    # 64-bit
 
# C++
i686-w64-mingw32-g++ helloWorld.cc -o helloWorld32.exe     # 32-bit
x86_64-w64-mingw32-g++ helloWorld.cc -o helloWorld64.exe   # 64-bit

Collected exe can be checked with wine.

Next, consider the changes to the CMake assembly, the CMakeLists.txt file, add MinGW specific things to the assembly file:


if (MINGW32)
set(CMAKE_SYSTEM_NAME Windows)
SET(CMAKE_C_COMPILER i686-w64-mingw32-gcc)
SET(CMAKE_CXX_COMPILER i686-w64-mingw32-g++)
SET(CMAKE_RC_COMPILER i686-w64-mingw32-windres)
set(CMAKE_RANLIB i686-w64-mingw32-ranlib)
endif()

elseif (MINGW32)
add_library(FlameSteelEngineGameToolkit.dll SHARED ${SOURCE_FILES})
else()

// link with all dependencies
if (MINGW32)
target_link_libraries(
                        FlameSteelEngineGameToolkit.dll 
                        -static-libgcc
                        -static-libstdc++
                        SDL2 
                        SDL2_mixer 
                        /home/demensdeum/Sources/cube-art-project-bootstrap/FlameSteelFramework/FlameSteelCore/FlameSteelCore.dll
                        /home/demensdeum/Sources/cube-art-project-bootstrap/FlameSteelFramework/FlameSteelBattleHorn/FlameSteelBattleHorn.dll
                        /home/demensdeum/Sources/cube-art-project-bootstrap/FlameSteelFramework/FlameSteelCommonTraits/FlameSteelCommonTraits.dll)

set_target_properties(FlameSteelEngineGameToolkit.dll PROPERTIES
        PREFIX ""
        SUFFIX ""
        LINK_FLAGS "-Wl,--add-stdcall-alias"
        POSITION_INDEPENDENT_CODE 0 # this is to avoid MinGW warning; 
        # MinGW generates position-independent-code for DLL by default
)
else()

Build:


cmake -DMINGW32=1 .
make

The output will be dll or exe, depending on your build. You can look at the working example in the repository of the new Cube-Art-Project and its libraries:
https://gitlab.com/demensdeum/cube-art-project
https://gitlab.com/demensdeum/FlameSteelEngineGameToolkitFSGL
https://gitlab.com/demensdeum/cube-art-project-bootstrap

References
https://arrayfire.com/cross-compile-to-windows-from-linux/

0

Simple Emscripten auto test with ChromeDriver

In this article, I will describe the implementation of running autotest for ChromeDriver of the Chrome browser, which runs the module autotest translated from C ++ using Emscripten, reads the console output and returns the result of the check.
First you need to install selenium, for python3-ubuntu this is done like this:


pip3 install selenium

Next, download ChromeDriver from the official site, put the chromedriver in / usr / local / bin for example, after which you can start implementing the autotest.
Below I will give the autotest code that launches the Chrome browser with the autotest page open on Emscripten, checks for the presence of the text “Window test succeded”:


import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

capabilities = DesiredCapabilities.CHROME
capabilities['goog:loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome()
driver.get("http://localhost/windowInitializeTest/indexFullscreen.html")

time.sleep(2)

exitCode = 1

for entry in driver.get_log('browser'):
    if entry["source"] == "console-api":
        message = entry["message"]
        if "Window test succeded" in message:
            print("Test succeded")
            exitCode = 0

driver.close()
exit(exitCode)

Save the test as main.py and run python3 main.py

0

Building project with libraries Emscripten

In this article, I will describe the assembly of a project consisting of several libraries using Emscripten.
Emscripten does not currently support building shared libraries, so the first thing we do is translate all the libraries from Shared to Static. Emscripten works with its include files, so you need to solve the issue with the visibility of header files, I solved it by forwarding the symlink from the system directory to the Emscripten toolchain:


ln -s /usr/local/include/FlameSteelFramework $EMSDK/fastcomp/emscripten/system/include/FlameSteelFramework

If you use CMake, then you need to change SHARED-> STATIC in the CMakeLists.txt file of the add_library method. To build a library / application for further static linking, use the commands:


emcmake cmake .
emmake make

Next, you will need to build the main application indicating * .a library files at the linking stage. I could not indicate the relative path, the assembly completed correctly only after specifying the full paths in the CMakeLists.txt file:


elseif(EMSCRIPTEN)
target_link_libraries(${FSEGT_PROJECT_NAME} GL GLEW 
/home/demensdeum/Sources/cube-art-project-bootstrap/cube-art-project/sharedLib/libCubeArtProject.a 
/home/demensdeum/Sources/cube-art-project-bootstrap/FlameSteelFramework/FlameSteelEngineGameToolkitFSGL/libFlameSteelEngineGameToolkitFSGL.a 
/home/demensdeum/Sources/cube-art-project-bootstrap/FlameSteelFramework/FlameSteelEngineGameToolkit/libFlameSteelEngineGameToolkit.a 
/home/demensdeum/Sources/cube-art-project-bootstrap/FlameSteelFramework/FlameSteelCore/libFlameSteelCore.a 
/home/demensdeum/Sources/cube-art-project-bootstrap/FlameSteelFramework/FlameSteelBattleHorn/libFlameSteelBattleHorn.a 
/home/demensdeum/Sources/cube-art-project-bootstrap/FlameSteelFramework/FSGL/libFSGL.a 
/home/demensdeum/Sources/cube-art-project-bootstrap/FlameSteelFramework/FlameSteelCommonTraits/libFlameSteelCommonTraits.a)
else()

References

https://emscripten.org/docs/compiling/Building-Projects.html#using-libraries

0

Shared Library CMake C++

Recently I decided to make all parts of FlameSteelFramework separate shared libraries, then I will show an example of a CMakeLists.txt file for FlameSteelCore:


cmake_minimum_required(VERSION 3.5)

project (FlameSteelCore)
set(CMAKE_BUILD_TYPE Release)

include_directories(${CMAKE_CURRENT_SOURCE_DIR}/src)

file(GLOB_RECURSE SOURCE_FILES
    "src/FlameSteelCore/*.cpp"
)

add_library(FlameSteelCore SHARED ${SOURCE_FILES})

install(DIRECTORY "${CMAKE_SOURCE_DIR}/src/FlameSteelCore"
        DESTINATION include/FlameSteelFramework
        FILES_MATCHING
        PATTERN "*.h"
)

install(TARGETS FlameSteelCore DESTINATION lib)

The commands that CMake executes are: it collects all files with the * .cpp extension from the src / FlameSteelCore / directory in the shared library, copies all readers with the * .h extension from src / FlameSteelCore to include / FlameSteelFramework (in my case it is / usr / local / include / FlameSteelFramework), copy shared lib to the lib directory (/ usr / local / lib)
After installation, it may be necessary to update the LD cache – sudo ldconfig.
To build and install on Ubuntu (if you have the correct build toolchain), just run the following commands:


cmake . && make && sudo make install

To check the installation process, I pass make prefix to the local makeInstallTestPlayground folder:


cmake -DCMAKE_INSTALL_PREFIX:PATH=/home/demensdeum/makeInstallTestPlayground . && make && make install

References

https://stackoverflow.com/questions/17511496/how-to-create-a-shared-library-with-cmake
https://stackoverflow.com/questions/6003374/what-is-cmake-equivalent-of-configure-prefix-dir-make-all-install

0

Cling – C++ interpreter

Not so long ago I came across an interesting project called Cling , a C ++ language interpreter that can work interactively from the console as well. You can check project here: https://github.com/root-project/cling
The installation for Ubuntu is the simplest – download the archive for the version you need, unzip it, go to the bin folder and run cling in the terminal.
The following is an example of loading the FlameSteelCore library, initializing the object, listing id:

0

Webassembly lost exceptions and regex troubles

Lost exceptions

An interesting feature of Emscripten, when starting a game loop through emscripten_set_main_loop, remember that exception handling must be re-added via try catch directly in the loop method, as runtime loses the try catch block from the outside.
The easiest way is to display the error text using the browser using javascript alert:


            catch (const std::exception &exc)
            {
                const char *errorText = exc.what();
                cout << "Exception: " << errorText << "; Stop execution" << endl;

                EM_ASM_(
                {
                    var errorText = UTF8ToString($0);
                    alert(errorText);

                }, errorText);

                abort();

Too complicated regexp

The regex implementation in std may throw an error_complexity exception if it finds the regex too complex. This happens in the current emscripten implementation, so I suggest you implement tests for parsing through regular intervals, or use third-party regex implementations.

0

Builder Pattern

The Builder pattern belongs to a group of patterns whose existence is not particularly clear to me, I note a clear redundancy of this. Refers to a group of generative design patterns. Used to implement a simple interface for creating complex objects.

Usage

Simplification of the interface. It can facilitate the creation of an object in constructors with a large number of arguments, objectively improve the readability of the code.

C ++ example without a builder:


auto monster = new Monster();
auto weapon = new Weapon(“Claws”);
monster->weapon = weapon;
auto health = new MonsterHealth(100);
monster->health = health;

C ++ example with a builder:


auto monster = new MonsterBuilder()
              .addWeapon(“Claws”)
              .addHealth(100)
              .build();

However, in languages ​​that support named arguments, there is no need to use it for this particular case.

Swift example using named arguments:


let monster = Monster(weapon: “Claws”, health: 100)

Immutability. Using the builder, you can ensure the encapsulation of the created object, until the final stage of assembly. Here you need to think carefully about whether the use of the pattern will save you from the high dynamics of the environment in which you work, perhaps the use of the pattern will not work, due to the simple lack of culture of using encapsulation by the development team.

Interaction with components at different stages of creating an object. Also, using the pattern, it is possible to provide step-by-step creation of an object when interacting with other components of the system. Most likely it is very useful (?)

Critics

Of course you need to * thoroughly * think about whether it is necessary to establish the widespread use of the pattern in your project. Languages ​​with modern syntax and an advanced IDE eliminate the need to use the Builder in terms of improving the readability of the code (see paragraph on named arguments)
Was it necessary to use this pattern in 1994, at the time of the release of the GoF book? Most likely yes, however, judging by the Open source code base of those years, few people used it.

References

https://refactoring.guru/design-patterns/builder

0

Composite Pattern

The Composite pattern refers to structural design patterns.
Suppose we are developing an application – a photo album. The user can create folders, add photos there, and perform other manipulations. You definitely need the ability to show the number of files in folders, the total number of all files and folders.
Obviously, you need to use a tree, but how to implement the architecture of the tree, with a simple and convenient interface? The Composite pattern comes to the rescue.

Sheila in Moonducks

Next, in the Directory, we implement the dataCount () method – by passing through all the elements lying in the component array, adding all their dataCount’s.
Done!
Go example:

package main

import "fmt"

type component interface {
    
    dataCount() int
    
}

type file struct {
    
}

type directory struct {

    c []component

}

func (f file) dataCount() int {

    return 1

}

func (d directory) dataCount() int {
    
    var outputDataCount int = 0
    
    for _, v := range d.c {
        outputDataCount += v.dataCount()
    }
    
    return outputDataCount
    
}

func (d *directory) addComponent(c component) {

    d.c = append(d.c, c)

}

func main() {
    
    var f file
    var rd directory
    rd.addComponent(f)
    rd.addComponent(f)
    rd.addComponent(f)
    rd.addComponent(f)

    fmt.Println(rd.dataCount())
    
    var sd directory
    sd.addComponent(f)
 
    rd.addComponent(sd)
    rd.addComponent(sd)
    rd.addComponent(sd)
    
    fmt.Println(sd.dataCount())
    fmt.Println(rd.dataCount())

}

References

https://refactoring.guru/design-patterns/composite

0