MinGW/GCC: error: stdlib.h: No such file or directory in include_next

A common error with MinGW or GCC is the following:

C:\...\lib\gcc\x86_64-w64-mingw32\7.2.0\include\c++\cstdlib:75: error: stdlib.h: No such file or directory
at #include_next 

This is typically due to the fact that something messed up the system include path with -isystem. Specifying again some paths changes the search order, so that #include_next doesn’t find what it is supposed to.

If you use CMake, a workaround is to set CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES and CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES to the list of default system paths. CMake will then not pass it the the compiler anymore. It will still use them, in the correct, hard-coded order.

Instead of hard-coding these paths in you CMakeList file, you can retrieve them automatically from the C preprocessor:

if("${CMAKE_MINGW_IMPLICIT_INCLUDE_DIRECTORIES}" STREQUAL "")
    # Run the preprocessor in verbose mode on an empty input
    execute_process(
        COMMAND
            "${CMAKE_CXX_COMPILER}"
            "-E"
            "-Wp,-v"
            "-"
        INPUT_FILE "NUL" # Special Windows file, equivalent to /dev/null
        OUTPUT_VARIABLE _mingw_cpp_out # Capture stdout
        ERROR_VARIABLE _mingw_cpp_error # Capture stderr
    )
 
    # Create list of lines from stderr output:
    string(REGEX REPLACE ";" "\\\\;" _mingw_cpp_error "${_mingw_cpp_error}")
    string(REGEX REPLACE "\n" ";" _mingw_cpp_error "${_mingw_cpp_error}")
 
    # Look for this text block and gather the paths:
    #   #include  search starts here:
    #   C:/..../bin/../lib/gcc/x86_64-w64-mingw32/7.2.0/include
    #   C:/..../bin/../lib/gcc/x86_64-w64-mingw32/7.2.0/include-fixed
    #   C:/..../bin/../lib/gcc/x86_64-w64-mingw32/7.2.0/../../../../x86_64-w64-mingw32/include
    #   End of search list.
    set(_mingw_cpp_list)
    foreach(_mingw_cpp_line ${_mingw_cpp_error})
        if("${_mingw_cpp_line}" MATCHES "#include  search starts here:")
            # Block starts
            set(_mingw_cpp_state "ON")
        elseif("${_mingw_cpp_line}" MATCHES "End of search list.")
            # Block ends
            set(_mingw_cpp_state "OFF")
        elseif("${_mingw_cpp_state}")
            # Within block
            # Clean up and beautify the path
            string(STRIP "${_mingw_cpp_line}" _mingw_cpp_line)
            get_filename_component(_mingw_cpp_line ${_mingw_cpp_line} REALPATH)
            list(APPEND _mingw_cpp_list ${_mingw_cpp_line})
        endif()
    endforeach()

    # Set the list in the cache, so that we don't have to run the external process again

    set(CMAKE_MINGW_IMPLICIT_INCLUDE_DIRECTORIES ${_mingw_cpp_list} CACHE INTERNAL "List of MinGW system include paths")
endif()

list(APPEND CMAKE_C_IMPLICIT_INCLUDE_DIRECTORIES ${CMAKE_MINGW_IMPLICIT_INCLUDE_DIRECTORIES})
list(APPEND CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES ${CMAKE_MINGW_IMPLICIT_INCLUDE_DIRECTORIES})

Advertisements
Posted in Uncategorized | Leave a comment

Building 32bit applications with mingw-w64 and CMake

The mingw-w64 provides ready-to-use packages with GCC for Windows. The toolchain is by default targeting the 64bit Windows architecture. It is possible to build 32bit binaries by using the -m32 option on the command line.

The toolchain can be easily integrated with CMake, however it gets more complicated when trying to build a 32bit application from CMake. After some trial and error, reading the documentation and debugging the CMake modules, I found out a simple solution that works for me:

    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32")

    project(MyProject ...)

    set_property(GLOBAL PROPERTY FIND_LIBRARY_USE_LIB32_PATHS TRUE)

    find_library(gcc_lib libgcc_s_sjlj-1.dll)
    find_library(cpp_lib libstdc++-6.dll)
    find_library(pthread_lib libwinpthread-1.dll)

Some notes:

    • According to the CMake documentation, CMake should set “FIND_LIBRARY_USE_LIB32_PATHS” automatically because MinGW requires it, but as of now (mingw-7.2.0 and CMake 3.12), it is not the case. So set it explicitly. Without this, find_library() will happily find the 64bit version of the libraries in the MinGW installation, causing linker errors.
    • Not sure if this is really required, but I set CMAKE_C_FLAGS and CMAKE_CXX_FLAGS before the project() statement, because in project(), CMake will look for the compiler and retrieve the library locations by introspection. If the -m32 flag is not used by then, CMake may find and use the location of the 64bit libraries, also causing linker errors later on
Posted in C/C++ | Leave a comment

Building protobuf with MinGW

Even if the documentation of the project doesn’t mention it, building protobuf with MinGW is easy when using CMake. The CMakeLists.txt is located in the “cmake” subdirectory.

I used following versions:

  • MinGW 7.2.0 (64 bit)
  • CMake 3.12.1
  • Protobuf 3.6.1

Two workarounds are however required with these versions:

Add “-DCMAKE_NO_SYSTEM_FROM_IMPORTED=ON” to the CMake command line to avoid the error:

fatal error: stdlib.h: No such file or directory
#include_next 

See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70129 for more information

Also, you will need to apply this patch to cmake/tests.cmake:

# Patch from commit a69dfe63bc26c12fd2786aec9239076997110315
# https://github.com/protocolbuffers/protobuf/commit/a69dfe63bc26c12fd2786aec9239076997110315#diff-f9c045cbe267fdd0dfff7a28d4b5365e
if(MINGW)
  set_source_files_properties(${tests_files} PROPERTIES COMPILE_FLAGS "-Wno-narrowing")

  # required for tests on MinGW Win64
  if (CMAKE_SIZEOF_VOID_P EQUAL 8)
    set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--stack,16777216")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wa,-mbig-obj")
  endif()

endif()
Posted in C/C++ | Leave a comment

Groovy: cloning nodes in an XML document

It’s pretty easy to clone nodes in a XML document using Groovy once XmlParser is used instead of XmlSlurper:

import groovy.xml.XmlUtil

def original = """
<catalog>
   <book id="sample">
      <author>sample</author>
      <title>sample</title>
   </book>
</catalog>
"""

def catalog = new XmlParser().parseText( original )

def sampleBook = catalog.book.find { it.@id == "sample" }

catalog.remove(sampleBook)

3.times {
  def c = sampleBook.clone()
  c.@id = "$it"
  c.author[0].value = "Author $it"
  c.title[0].value = "Title $it"

  catalog.append(c)
}

println XmlUtil.serialize(catalog)


The result is:

<?xml version="1.0" encoding="UTF-8"?><catalog>
  <book id="0">
    <author>Author 0</author>
    <title>Title 0</title>
  </book>
  <book id="1">
    <author>Author 1</author>
    <title>Title 1</title>
  </book>
  <book id="2">
    <author>Author 2</author>
    <title>Title 2</title>
  </book>
</catalog>

 

Posted in Uncategorized | Leave a comment

Apache: undefined symbol: ap_proxy_location_reverse_map

If you get the following error when starting Apache:

apache2: Syntax error on line ...:
Cannot load mod_proxy_http.so into server:
mod_proxy_http.so: undefined symbol: ap_proxy_location_reverse_map

…then make sure that mod_proxy is enabled, and that it is loaded BEFORE mod_proxy_http. Apache doesn’t support dependency management of modules, so they have to be enabled in the appropriate order.

You might want to disable the modules and reenable them in the right order with a2enmod, or change the order in for instance /etc/sysconfig/apache2

Posted in Linux | Leave a comment

VMWare Fusion: the path “” is not valid path to the gcc binary.

A common error installing the VMWare tools in a Ubuntu guest is:

Searching for GCC...
the path "" is not valid path to the gcc binary. 
Would you like to change it? [yes]

In some cases, like when using an older version of Fusion with newer version of Ubuntu, an easy workaround is to use the opensource version of the VMWare tools provided by the distribution:

apt-get install open-vm-tools open-vm-tools-desktop
Posted in Uncategorized | Leave a comment

PHP not working in Apache virtual hosts

I just had the situation where PHP worked fine from the default/main site configured in Apache, but not in a virtual host. Instead of parsing/executing the PHP script, Apache would rather send its source code back to the browser, which would propose to download it.

I found various potentials solutions online, like:

  • Checking if the PHP module was enabled (it was)
  • Setting “php_admin_flag engine” or “php_admin_value”  to “on” (it didn’t help)

What helped was to enable explicitly the PHP handlers in the Directory section of the corresponding vhosts. On OpenSUSE Leap, the file /etc/apache2/conf.d/php7.conf does exactly that, so I could just include it:

<VirtualHost ...>
        DocumentRoot /some/path
        <Directory /some/path>
                Include /etc/apache2/conf.d/php7.conf
                Options ...
                AllowOverride ...
                Require all granted
        </Directory>
</VirtualHost>
Posted in Uncategorized | Leave a comment

Uploading a file with HTTP PUT in Groovy with Basic Auth

Dependencies:

dependencies {
   compile 'org.codehaus.groovy.modules.http-builder:http-builder:0.7.1'
   compile 'org.apache.httpcomponents:httpmime:4.5'
}

Code:

import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import org.apache.http.client.entity.EntityBuilder
import org.apache.http.util.EntityUtils


class HttpPut {
   File inputFile
   String url
   String username
   String password

   HttpPut withFile(File inputFile) {
       this.inputFile = inputFile
       return this
   }

   HttpPut withUrl(String url) {
       this.url = url
       return this
   }

   HttpPut withCredentials(String username, String password) {
       this.username  = username
       this.password = password
       return this
   }

   void put() {
       def http = new HTTPBuilder(url)

       http.auth.basic(username, password)

       http.request(Method.PUT) { request ->
           request.entity = EntityBuilder.create().setBinary(inputFile.bytes).build()
       }
   }
} 

Posted in Uncategorized | Leave a comment

Gerrit: robust regular expression to create links from text automatically (commentlink)

When there is a link to a bug tracking ticket in a commit message, and Gerrit is already configured to make links out of ticket numbers automatically, it results in a mess. There is a bug report about this since quite a while already, but no progress yet.

A workaround is to use a lookbehind regular expression, to ignore ticket numbers that are followed by a double quote or

</a>

, because they are most likely part of a generated URL.

For Jira issue IDs, it would look like this:

[commentlink "bugtracking"]
       match = \\b([A-Z][A-Z0-9]+-\\d+)(?!(\"|))
       link = https://jira/path/$1

If you need to troubleshoot this kind of issue: it is very cumbersome to test the regex directly in Gerrit, because you have to modify the config file, stop Gerrit, flush the caches and restart it. Since the regex syntax is the one of Javascript, you can use a tool like https://regex101.com. Just enter as test string a set of lines you want to match, another set that you don’t want to match, enable the “g” option, and experiment with the regular expression until it works as expected. Then you need only to escape the \ and the ” and put it in the Gerrit config file.

Posted in Uncategorized | Leave a comment

Notepad++: automatic configuration of tabs vs. spaces

Notepad++ is a great text editor with lots of features out of the box, but I miss particularly one: the ability to use automatically tabs or spaces for indentation according to the content of an existing file when opening it.

Luckily enough, it’s easy to add this feature using the Python scripting plugin.

  • Install the Python scripting add on for Notepad++ with the plugin manager
  • Open C:\Program Files (x86)\Notepad++\plugins\PythonScript\scripts\startup.py
  • Append the code below at the bottom of the file
  • Save the file
  • Open Notepad++
  • Choose Plugins -> Python Script -> Configuration
  • Ensure Initialisation is set to ATSTARTUP and save
  • Restart Notepad++
from Npp import *

def indent_auto_detect(arg):
    for i in range(editor.getLineCount()):
        pos = editor.positionFromLine(i)
        indent = editor.getLineIndentPosition(i)-pos
        if indent > 0:
            if ord('\t') == editor.getCharAt(pos):
                console.write("Indentation: Tabs\n")
                editor.setUseTabs(True)
                return
            elif indent in [2, 3, 4, 8]:
                console.write("Indentation: %d spaces\n" % indent)
                editor.setUseTabs(False)
                editor.setIndent(indent)
                return

notepad.clearCallbacks([NOTIFICATION.BUFFERACTIVATED, NOTIFICATION.READY])
notepad.callback(indent_auto_detect, [NOTIFICATION.BUFFERACTIVATED])
notepad.callback(indent_auto_detect, [NOTIFICATION.READY])
console.write("Automatic indentation detection started\n")
indent_auto_detect(None)

The code comes from: https://gist.github.com/patstew/8dc8a4c0b816e2f33204e3e15cd5497e

Posted in Uncategorized | 1 Comment