Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine which header files to include?

Tags:

c++

Say I have the below (very simple) code.

#include <iostream>
int main() {
    std::cout << std::stoi("12");
}

This compiles fine on both g++ and clang; however, it fails to compile on MSVC with the following error:

error C2039: 'stoi': is not a member of 'std'

error C3861: 'stoi': identifier not found

I know that std::stoi is part of the <string> header, which presumably the two former compilers include as part of <iostream> and the latter does not. According to the C++ standard [res.on.headers]

A C++ header may include other C++ headers.

Which, to me, basically says that all three compilers are correct.

This issue arose when one of my students submitted work, which the TA marked as not compiling; I of course went and fixed it. However, I would like to prevent future incidents like this. So, is there a way to determine which header files should be included, short of compiling on three different compilers to check every time?

The only way I can think of is to ensure that for every std function call, an appropriate include exists; but if you have existing code which is thousands of lines long, this may be tedious to search through. Is there an easier/better way to ensure cross-compiler compatibility?

Example with the three compilers: https://godbolt.org/z/kJhS6U

like image 844
ChrisMM Avatar asked Nov 27 '19 12:11

ChrisMM


1 Answers

Is there an easier/better way to ensure cross-compiler compatibility?

This is always going to be a bit of a chore if you have a huge codebase and haven't been doing this so far, but once you've gone through fixing your includes, you can stick to a simple procedure:

When you write new code that uses a standard feature, like std::stoi, plug that name into Google, go to the cppreference.com article for it, then look at the top to see which header it's defined in.

Then include that, if it's not already included. Job done!

(You could use the standard for this, but that's not as accessible.)

Do not be tempted to sack it all off in favour of cheap, unportable hacks like <bits/stdc++.h>!


tl;dr: documentation

like image 136
Lightness Races in Orbit Avatar answered Oct 16 '22 15:10

Lightness Races in Orbit