How to make sure code (c++) written in Xcode can compile on other platforms? - c++

I am a beginner was trying to do some C++ programming on Xcode. It works fine, but when I try to compile the same c++ file on my windows pc using VS, there were some errors. After I look at my code closely, there are really some stupid mistakes that I have made which caused the errors, but Xcode seemed to have ignored them...
My question is that is there any setting that I need to change to prevent Xcode from being so smart?
For example, the following code can actually compile in xcode:
#include <iostream>
using namespace std;
int main() {
if (true or false){
cout << "How is this possible? \n";
}
return 0;
}
There are also other cases where the code is actually wrong, but it can compile just fine is Xcode which is the annoying part and I want to disable that.

As far as I can see there is nothing wrong with your code.
The ISO C++ standard does not specify which standard headers are included by other standard headers. So, it is entirely possible that the version of iostream used by Xcode directly or indirectly includes ciso646. Whereas Visual Studio's version of iostream does not include ciso646. There are many similar cases with other headers. You just need to read the error messages and realize that your error (when you move your file to a different platform) is due to a missing header file.

It would be nice if writing portable code meant writing code in accordance with the C++ standard specification, but unfortunately that's not the case. Although there are various compiler options on various implementations which can help bring different implementations closer together, in general you will just have to bring the code into the target environment and actually test it there.
So ultimately writing portable code means you'll have to learn some subset of C++ that is accepted by all the implementations you want to target.
or is an 'alternative token' in C++, and VS is incorrect to reject it. There's no option in Xcode to disable support for alternative tokens. However VS has non-standard support for or as a macro using the header <ciso646>, and Xcode does have a header <ciso646> which does nothing (as the standard specifies). So you can write code which uses or and which works in both Xcode and VS by including this header.
#include <iostream>
#include <ciso646> // does nothing in Xcode, allows `or` in VS
using namespace std;
int main() {
if (true or false){
cout << "How is this possible? \n";
}
return 0;
}
Unfortunately VS can't support all of the alternative tokens through macros and so Xcode will still support some that VS doesn't.
There are also other cases where the code is actually wrong, but it can compile just fine is Xcode which is the annoying part and I want to disable that.
If you give specific examples then I can provide additional advice on how to write portable code.

Rather than changing your Xcode settings, I suggest cross-checking your code using another development environment.
If you're looking for something cheap and full-proof. Download a VirtualBox Windows VM, and run download Dev C++ (bloodhshed)

VS does not support or: you need to use || instead.
You can include some special files but it doesn't inject or sufficiently well into the language for it to work in all instances.
If you want to suppress use of or (and your compiler supports no better way)
#define it to something that emits a compiler error, for example
#define or OR
This at least means that the nature of the compilation errors will be identical on Xcode and VC.

Related

Dev C++ compiler file is used in VS Code

I have set Dev C++ Compiler MinGW bin folder as Enviroment Variable Path, So that i can use it in cmd and VS Code terminal also, But it compiles well and only performs simple operations.** It cannot give class object function output
**
Path which i have added C:\Program Files (x86)\DevC++\MinGW\bin
#include <iostream>
using namespace std;
class Base{
public:
void greet(void){
cout<<"How are You ? \n"<<endl;
}
};
int main(){
Base obj;
cout<<"Good Morning!\n";
obj.greet();
return 0;
}
Output:
Good Morning!
Expect Output:
Good Morning!
How are you ?
I want to know if it is same compiler file of MinGW in DevC++ why cannot we use outside DevC++, why do i have to download seperate compiler for VS Code.
The IDE you're using (Dev C++ / VS Code) doesn't really matter that much with regards to your issue, what does matter is the compiler.
Make sure to not mix compilers, certainly if their versions very much apart.
And Dev C++ is shipped with an old version.
I recommend using a newer MinGW-w64 compiler - you can get a standalone version fro https://winlibs.com/ - and configuring your IDEs (both Dev C++ and VS Code) to use this same compiler.
Only then can you be sure you're linking things together that play well together (unless you're still pulling in other dependencies build with different compilers).

VSCode C++ Intellisense can't discern C++20 features

I try to run codes like
#include <string>
#include <iostream>
int main() {
std::string str = "This is a string";
std::cout << str.starts_with("name");
}
But intellisense will give out an error
"std::__cxx11::basic_string<char, std::char_traits,
std::allocator>" has no member "starts_with" C/C++(135) [6,9]
And It still can be build and produce a correct result.
Also it can find implementation in header file.
But the macro __cplusplus is defined as 201703L
I've already added a command -std=c++20 when building, why this happened?
Compiler: minGW 11.2 compiled by msys2
Assuming you are using Microsoft's C/C++ extension, you must configure the extension to use C++ 20 standard for intellisense.
The easiest way to do this is to add the line "C_Cpp.default.cppStandard": "c++20" to your settings.json file. You can also find the setting in the GUI under the name "Cpp Standard". Selecting c++20 from its dropdown will achieve the same result.
Note that this setting is, by default, set as a global user defaults. You can configure it per-workspace by selecting the Workspace tab in the settings GUI and changing that Cpp Standard dropdown to c++20.
As for why adding the -std=c++20 flag didn't work: -std=c++20 just tells your compiler which standard to use to build your code. 'Intellisense' does not receive this flag because it is a separate tool from the compiler and is therefore not required to support all the standards the compiler supports. It may support less even, although Intellisense tools usually support as current a standard as possible. Therefore the language standard for Intellisense must be configured separately from the compiler (in this case).
Final Note: After changing the setting, try closing and re-opening VS Code. In my experience changing the language standard setting can cause some weirdness to happen. Closing and re-opening VS Code seems to ensure the setting changes take full effect.

MSVC C++ compiler option to prevent replacing LF by CR LF in ostream/ofstream

I'm using Microsoft Visual Studio 2017's command line tools such as cl.exe to compile C++ codes.
Instructions to output line breaks like
std::cout << "abc" << std::endl;
or
std::cout << "abc" << '\n';
or
printf("abc\n");
result in "abc\r\n" instead of "abc\n".
How can I change this behavior to get "abc\n" output?
If possible, I want it to be realized without making a big change to the core C++ source code like adding "binary mode" flag to everywhere an output stream is created. (I already have a relatively large C++ project which is fine with GCC and trying to build it with MSVC)
There's no way to achieve this with Standard C++. Apparently there's no way to achieve this with implementation specific documented functions. If it is possible, it will rely on implementation details.
You may hook CRT functions fopen, _wfopen, fopen_s, wfopen_s, in hooked function you would alter open mode. C++ streams internally use those functions as well.
How exactly to do it will depend on whether you link CRT statically or dynamically and which version of Visual Studio you use.
I want it to be realized without making a big change to the core C++ source code like adding "binary mode" flag to everywhere an output stream is created.
There's no correct way other than fixing your buggy code. There shouldn't be a lot of places that open files so just fix that manually. You don't open tens of thousands of files at a time, do you?
That said, if you really want to use LF everywhere in the C++ streams then the Microsoft STL is open source. You can download the STL, patch it and use that one instead of the shipped version in MSVC. The C standard libraries aren't open sourced so you'll have to fix the C part manually, if any
However even if you patch the STL, the source code or the output binary to make it always use LF instead of CRLF then lots of other functionalities will fail, for example console output won't work properly. This is also highly fragile because new code or new 3rd party libraries added in the future might break because they don't expect LF, so beware of that
I already have a relatively large C++ project which is fine with GCC and trying to build it with MSVC
Line ending has nothing to do with the compiler. Even if you build with GCC on Windows then it'll still use CRLF. It's a platform property
You can prevent this via _setmode which you can call at the beginning of your program (watch out for global constructors which might already print something):
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#endif
int main() {
#ifdef _WIN32
_setmode(_fileno(stdout), _O_BINARY);
#endif
// ...
}

C++ namespace "hiding" appearing in the Eclipse parser

Recently I have being working on a project using C++ as the programming language and Eclipse CDT as the programming IDE. The 'Chrono' library is used in the project.
I was trying to define the "<<" stream operator for different time scales like nanoseconds by putting the definitions in the same namespace as chrono, namely "std::chrono". One small example of the code of the header file (Test.hpp) is illustrated as following:
#include <chrono>
#include <iostream>
namespace test{ namespace chrono{
typedef std::chrono::nanoseconds nanoseconds;
}}
namespace std{ namespace chrono{
inline std::ostream& operator<<(std::ostream& s, nanoseconds dur)
{
return s << dur.count() << "ns";
}
}}
The above code together with other parts of the project can be compiled correctly. However, the IDE, Eclipse CDT, keeps complaining "Type 'std::chrono::nanoseconds' could not be resolved" and the auto-completion functionality says "No Default Proposals" for any member variables/functions in the namespace "std::chrono". It looks like that adding new functions into the "std::chrono" namespace in this header file somehow 'hides' other content from the Eclipse's point of views.
The question is what could be the reason leading to such 'error' messages in Eclipse CDT or it is one flaw in my programming? I would appreciate any help or hint from you.
I also copy-past the code into Xcode on the laptop and there is no such error message as in Eclipse CDT.
Additional information:
The os I am using is Mac OS, thus the chrono library is slightly different from that mentioned in the answer. The screenshot of 'chrono.hpp' is as following:
Actually, my CDT has no issue to find the members in the namespace 'std::chrono::'. What confuses me is CDT's behaviour when I add/override members in the namespace 'std::chrono::'. See the following pictures:
Errors appear when I override a member function in the namespace:
Errors do not appear when I do nothing on the namespace:
Any idea on how to solve this problem?
Assumptions about your setup
I believe you have changed your build settings to use -std=c++0x or something similar as the chrono library requires it.
Perhaps you did it like this:
At the top of chrono (header file) there is a bit like this:
#if __cplusplus < 201103L
# include <bits/c++0x_warning.h>
#else
so that if you don't have sufficiently new C++ standard, you get a compile error.
Now the problem is the CDT indexer that is used to generate highlighting and code completions does not know you are using __cplusplus >= 201103L. You can see this in this following screenshot that the majority of chrono is inactive because __cplusplus is the wrong value.
This screenshot shows the incorrect value and the errors CDT identifies:
And if you try and code complete, you get the wrong thing too:
How to fix it
To fix the problem, you need to tell CDT that your project uses GCC settings that are different from the default GCC settings. i.e. because of the different standard __cplusplus in particular has the wrong value.
In Project Properties, choose C/C++ General -> Preprocessor Includes and then the Providers tab.
Choose the CDT GCC Built-in Compiler Settings
Uncheck the Use global provider shared between projects
Press OK
Here is a screenshot of what that looks like:
Once you do this, you should see that chrono's inactive sections becomes correct in the editor:
But your source file may still be wrong. You should then rebuild the indexes to update, right-click on the project, choose Index -> Rebuild:
Finally your code should not display properly:
And the code complete should be working too!
History
This is a case where CDT's right hand and left hand don't agree. Historically I believe the reasoning for this is down to performance and trading off indexing every possible variant of compiler/user option, vs having some shared data across the workspace that may be wrong for some projects.

How to Make Visual Studio C++ 2010 Compilation Behave Like gcc/g++? (or vice-versa)

Say you've got the following simple main.cpp file:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
const string FILENAME = "foo.txt";
ifstream somefile(FILENAME);
populations.close();
return 0;
}
This compiles fine via Visual Studio C++ 2010.
However, on a Linux-based system, if I execute make main and compile, we get an expected error since we didn't call c_str() on the string constant, like so:
ifstream somefile(FILENAME.c_str());
As is commonly known, and described in this SO thread.
How can I get VS to behave like gcc/g++ and raise a compilation error for the code above? Or, how can I get gcc/g++ to behave like VS and compile the above without error? (Is it a simple matter of upgrading my gnu compiler?)
(I don't believe disabling compiler extensions is a solution, as I've done this and it still compiles without error.)
Visual Studio behaves correctly in this case with respect to the C++11 standard (it works on g++ now, too). I'm not sure why would you want to do this, but you'll probably need to edit MSVC's headers (not advisable and rather drastic).
Strange thing is though, that they don't write it in their documentation. Can you check which constructor is actually being called?
It is available as part of the newer c++ standard.
To disable, add
#define _HAS_CPP0X 0
at the top before your includes.