Disable Eclipse's error discovery. (Codan false positives) - c++

My experience until now is, that the error discovery of Eclipse is horribly buggish without any solutions (Tried __GXX_EXPERIMENTAL_CXX0X__, -std=c++0x, -std=c++11 in nearby every point of the settings). I am at the point that I dont want to search for a solution no more. Now I just want to see solely real compiler errors. But how to accomplish this?

UPDATE: It's been a long time since I posted the original answer and it has become outdated. I double-checked today (Mar 15, 2014): in Eclipse Kepler (Build id 20130614-0229) it is sufficient to
add under Project > Properties > C/C++ Build > Settings then on the Tool Settings tab GCC C++ Compiler > Miscellaneous the -std=c++11 flag,
then under Window > Preferences > C/C++ > Build > Settings on the Discovery tab chose CDT GCC Built-in Compiler Settings and add the -std=c++11 flag to Command to get compiler specs. On my machine it looks like this after the change:
${COMMAND} -E -P -v -dD -std=c++11 "${INPUTS}"
clean and rebuild both your project and your index (Project > C/C++ Index > Rebuild) as Eclipse tends to cache error messages and show them even though they are gone after changing the settings.
This works on my machine for sure. If it doesn't on yours, then you might want to give a shot to this: C++11 full support on Eclipse although I am neither sure about the correctness of this approach nor was it necessary to do it on my machine. As of March 7, 2014 users claim that it helped them whereas the above approach didn't.
The original post from 2012, now outdated:
These bogus errors come from Codan. I also issued a bug report (C++03!!!) but the same problem shows up in the latest stable Eclipse so I don't think much has happened :(
Workaround:
Click on the project properties, then C/C++ General > Code Analysis > Syntax and Semantic Errors and deselect whatever false errors you are getting.
I just want to see solely real compiler errors
Of course, you can disable there the static analysis completely, in that case you can accomplish exactly what you want.
UPDATE: 2 users have reported that what Jeevaka wrote helped them. I have tried what he wrote, it did not help me with Juno SR1 and CDT 8.1.1. Perhaps Codan developers have improved static analysis in Juno SR2 and CDT 8.1.2

I was troubled by Cordian errors for c++11 code that compile perfectly in gcc with all warnings enabled as well. I found what I think is the root cause, at least it was in my case. Few other questions on Cordian errors for c++11 are closed as duplicates of this question and point to this question. So I though I would post my answer here.
This is what I found:
Project Properties > C++ General > Preprocessor … > Entries > GNU C++ > CDT GCC Builtin Compiler Settings has *__cplusplus=199711L* as one of the entries.
I changed it as follows:
In the Window > Preferences > C/C++ > Build > Settings > Discovery tab selected CDT GCC Builtin Compiler Settings and changed ${COMMAND} -E -P -v -dD ${INPUTS} to ${COMMAND} -E -P -v -std=c++11 -dD '${INPUTS}'. Then hit Apply.
The errors were gone after next build.
I am using Juno SR2 with CDT 8.1.2 and handmade make files.
Adding a little more color:
I am no expert, but here is what I think happened in my case:
Cordian gather errors in multiple ways.
One is parsing the compiler output. -std=c++11 in my Makefile ensured that this part worked right all along as invoking the same Makefile through terminal didn't flag any errors.
Another is through 'Code Analysis'. For this, and probably for other tasks, Ecplise need to know the settings that compiler would use. Eclipse find these by invoking the command I edited above and parsing the output. By ticking the 'Allocate console in the Console View' before hitting 'Apply' it is possible to view the output of this command. These settings include include directories and defines such as __cplusplus. When these match what gcc would use when invoked through my Makefile the results are consistent.
When I was experimenting with the problem using #pragma message inside headers I thought __GXX_EXPERIMENTAL_CXX0X__ is what is wrong and saw some online suggestions for setting this manually, but that seemed to be a workaround as well.

On a fresh Eclipse install, triggering one macro and rebuilding the index solved it:
Projects->Properties->Preprocessor Includes
Select GNU C++
Select CDT User Setting entries
Press Add
and add a preprocessor macro with name __cplusplus and value 201103L.
Finally, rebuild the index.
(Project->C/C++ Index->Rebuild)

You can also remove problematic parts of code from the CDT scope by fllowing next steps:
Go to the Project Properties->C/C++ General->Preprocessor include path, Macros, etc
Select desired language on Entries tab
Add->Preprocessor macro
Enter name "MY_CODAN_MACRO" and value "1"
Now you can write:
#idndef MY_CODAN_MACRO
// this code is visible by compiler only
#else
// this code is visible by code analysis and CDT, but not visible by compiler
#endif
I think this trick is possible in Indigo+. I'm using Juno.

I realize question was asked a long time ago but since the problem persists (I user Kepler and get the same errors) I will post another possible workaround.
One can create separate source file and redefine functions he want to use there (in general namespace e.g.). After I created function like that
std::string to_string(long long num) {
return std::to_string(num);
}
and started to use to_string instead of std::to_string in main sources (I added the extra one with including) eclipse did not mark code as errors any more.
Of course the errors are marked in the extra include but it does not contain logic so you don't even look there.

Related

Eclipse C++: fatal error: cheddar.h: no such file or directory

[RHEL v7.3, Eclipse Photon, C/C++ Project with Eclipse-generated Makefile]
Attempting to include a custom library named cheddar.h results in
Fatal Error: cheddar.h: no such file or directory
Research 1 and 2 suggests manually adding the include path by first alt-clicking the project in Project Explorer, and then manually adding the path :
Properties -> C/C++ General -> Paths and Symbols : Includes : Languages, GNU C++
No luck.
It works if I do things the old-fashioned way, and add the path to the makefile with a -I option, like so
-I/home/kmiklas/lib/
..but I feel like I'm working-around the issue, and I want this set up properly; the way it should be set up.
How do I correctly specify a custom include path in Eclipse? Tyvm :^)
What is wrong with CMake/Makefile?
I don’t know, but this just sounds like an XY problem. But what’s even more confusing is how you’re so reluctant to use a solution that you’ve already got (as in it’s bugging me).
Anyway
What may aid you in this is to ditch eclipse’s settings and just use the compiler’s. Eclipse uses (GCC/G++ (probably)). What you can do is set some environment variables DUN DUN DUHH!
These environment variables are aptly named: C_INCLUDE_PATH and CPLUS_INCLUDE_PATH. If, however, you want the same for both (you want to use it for both languages) you can just set CPATH.
You’re probably thinking: what else can I do with this marvel... and for that I direct you to the official GCC website.

Custom autoformat in Xcode [duplicate]

As a C# developer, I have become highly dependent on the automatic formatting in Visual Studio 2008. Specifically, I will use the CTRL + K , D keyboard shortcut to force things back into shape after my sloppy implementation.
I am now trying to learn Objective-C and am missing certain features in Xcode, but probably none are quite as painful as the formatting shortcut. My Google searches have yielded nothing built in, though it seems there are some hacks. Am I missing something or does this feature not exist natively in Xcode?
That's Ctrl + i.
Or for low-tech, cut and then paste. It'll reformat on paste.
Unfortunately, Xcode doesn't have anything nearly as extensive as VS or Jalopy for Eclipse available. There are SOME disparate features, such as Structure > Re-Indent as well as the auto-formatting used when you paste code into your source file. I am totally with you, though; there definitely should be something in there to help with formatting issues.
I'd like to recommend two options worth considering. Both quite new and evolving.
ClangFormat-Xcode (free) - on each cmd+s file is reformatted to specific style and saved, easy to deploy within team
An Xcode plug-in to format your code using Clang's format tools, by
#travisjeffery.
With clang-format you can use Clang to format your code to styles such
as LLVM, Google, Chromium, Mozilla, WebKit, or your own configuration.
Objective-Clean (paid, didn't try it yet) - app raising build errors if predefined style rules are violated - possibly quite hard to use within the team, so I didn't try it out.
With very minimal setup, you can get Xcode to use our App to enforce
your rules. If you are ever caught violating one of your rules, Xcode
will throw a build error and take you right to the offending line.
In xcode, you can use this shortcut to Re-indent your source code
Go to file, which has indent issues, and follow this :
Cmd + A to select all source codes
Ctrl + I to re-indent
Hope this helps.
My personal fav PrettyC wantabe is uncrustify: http://uncrustify.sourceforge.net/. It's got a few billion options however so I also suggest you download UniversalIndentGUI_macx, (also on sourceforge) a GUI someone wrote to help set the options the way you like them.
You can then add this custom user script to uncrustify the selected text:
#! /bin/sh
#
# uncrustify!
echo -n "%%%{PBXSelection}%%%"
/usr/local/bin/uncrustify -q -c /usr/local/share/uncrustify/geo_uncrustify.cfg -l oc+ <&0
echo -n "%%%{PBXSelection}%%%"
You can use Command + A to select all content and next Ctrl + I to format the selected content.
I also feel xcode should have this function.
So I made an extension to do it: Swimat
Simple install by brew cask install swimat
You can give it a try, see https://github.com/Jintin/Swimat for more information.
Cmd A + Ctrl I
Or Cmd A And then Right Click. Goto Structure -> Re-Indent
Consider buying yourself a license for AppCode, an intelligent Objective-C IDE that helps iOS/OS X developers. AppCode is fully compatible with Xcode, but goes beyond Xcode in adding powerful features.
AppCode an Objective-C variant of the Intellij IDEA IDE from JetBrains. They are also authors of popular ReSharper extension to Visual Studio, which main purpose from here seems like a desperate attempt to bring a touch of IDEA experience to a Microsoft product.
AppCode is using its own code analyser which gives close-to-perfect refactoring and code navigation support. There is an ability to re-indent and completely reformat code also (although I still keep missing a couple of formatting settings in hard cases, but mostly it works well).
You might try the trial version, of course.
Swift - https://github.com/nicklockwood/SwiftFormat
It provides Xcode Extension as well as CLI option.
CTRL + i
that's it.
(no COMMAND + i)
You can also have a look at https://github.com/octo-online/Xcode-formatter which is a formatter based on Uncrustify and integrated into Xcode. Works like a charm.
You could try that XCode plugin https://github.com/benoitsan/BBUncrustifyPlugin-Xcode
Just clone github repository, open plugin project in XCode and run it. It will be installed automatically. Restart Xode before using formatter plugin.
Don't forget to install uncrustify util before. Homebrew, for exmaple
brew install uncrustify
P.S. You can turn on "after save formatting" feature at Edit > Format Code > BBUncrustifyPlugin Preferences > Format On Save
Hope this will be useful for u ;-)
I suggest using ClangFormat. In order to install, please follow these steps:
Install Alcatraz package manager for XCode
Supports Xcode 5+ & OS X 10.9+
After installation restart XCode.
Open XCode -> Window Menu -> Package Manager
Search (find) ClangFormat and install it. After installation again restart XCode.
Now at XCode menu you can use Edit -> Clang Format submenu for formatting.
You can choose different types of formatting. Also by enabling Format On Save you can gain auto-format capability.
If your Xcode version 3.x , you should use "User Script" With Uncrustify , here this a Example:
#!/bin/sh
echo -n "%%%{PBXSelection}%%%"
$YOURPATH_TO_UNCRUSTIFY/uncrustify -q -c $YOURPATH_TO_UNCRUSTIFY_CONFIG/CodeFormatConfig.cfg -l OC+
echo -n "%%%{PBXSelection}%%%"
add above to your Xcode "User Script".
if Xcode version 4.x , I think you should read this blog : Code Formatting in Xcode 4,
In this way , used the "Apple Services" , but it's not good enough , cause too slow experience, does anyone has the same thing ?
why apple drop "user script" .... xD
First, Examine XCode Preferences "Indentation" section. You can customize things quite a bit there...
For more fine grained control, refer to the XCode User Defaults document from apple. (May require a developer login to view). For example, I was able to disable the "indent on paste" by entering the following in terminal:
defaults write com.apple.XCODE PBXIndentOnPaste No
to read back your setting:
defaults read com.apple.XCODE PBXIndentOnPaste
This only works for languages with are not whitespace delineated, but my solution is to remove all whitespace except for spaces, then add a newline after characters that usually delineate EOL (e.g. replace ';' with ';\n') then do the ubiquitous ^+i solution.
I use Python.
Example code, just replace the filenames:
python -c "import re; open(outfile,'w').write(re.sub('[\t\n\r]','',open(infile).read()).replace(';',';\n').replace('{','{\n').replace('}','}\n'))"
It 's not perfect (Example: for loops), but I like it.
We can use Xcode Formatter which uses uncrustify to easily format your source code as your team exactly wants to be!.
Installation
The recommended way is to clone GitHub project or download it from https://github.com/octo-online/Xcode-formatter and add the CodeFormatter directory in your Xcode project to get :
Xcode shortcut-based code formatting: a shortcut to format modified sources in the current workspace
automatic code formatting: add a build phase to your project to format current sources when application builds
all sources formatting: format all your code with one command line
your formatting rules shared by project: edit and use a same configuration file with your project dev team
1) How to setup the code formatter for your project
Install uncrustify
The simplest way is to use brew:
$ brew install uncrustify
To install brew:
$ ruby –e “$(curl –fsSkl raw.github.com/mxcl/homebrew/go)”
Check that uncrustify is located in /usr/local/bin
$ which uncrustify
If your uncrustify version is lower than 0.60, you might have to install it manually since modern Objective-C syntax has been added recently.
Add CodeFormatter directory beside your .xcodeproj file
Check that your Xcode application is named "Xcode" (default name)
You can see this name in the Applications/ directory (or your custom Xcode installation directory). Be carefull if you have multiple instances of Xcode on your mac: ensure that project's one is actually named "Xcode"!
(Why this ? This name is used to find currently opened Xcode files. See CodeFormatter/Uncrustify_opened_Xcode_sources.workflow appleScript).
Install the automator service Uncrustify_opened_Xcode_sources.workflow
Copy this file to your ~/Library/Services/ folder (create this folder if needed).Be careful : by double-clicking the .workflow file, you will install it but the file will be removed! Be sure to leave a copy of it for other users.
How to format opened files when building the project
Add a build phase "run script" containing the following line:
sh CodeFormatter/scripts/formatOpendSources.sh
How to format files in command line
To format currently opened files, use formatOpenedSources.sh:
$sh CodeFormatter/scripts/formatOpendSources.sh
To format all files, use formatAllSources.sh:
$sh CodeFormatter/scripts/formatAllSources.sh PATH
PATH must be replaced by your sources path.
E:g; if project name is TestApp then the command will be
$sh CodeFormatter/scripts/formatAllSources.sh TestApp
it will look for all files in the project and will format all the files as configured in uncrustify_objective_c.cfg file.
How to change formatter’s rules
Edit CodeFormatter/uncrustify_objective_c.cfg open with TextEdit
Well I was searching for an easy way. And find out on medium.
First to copy the json text and validate it on jsonlint or something similar. Then to copy from jsonlint, already the json is formatted. And paste the code on Xcode with preserving the format, shortcut shift + option + command + v

How to remove error "unresolved inclusion" for user defined path in eclipse IDE

i have imported existing IAR C++ Project for ARM into eclipse IDE , with plugin added for IAR tool chain. The project got imported , but some files are not getting included. It gives error :Unresolved inclusion" and text is underlined with red color. I have added path for these files as shown below but still same error is there . Please suggest for removing this error.
include "./../../../try_one/try_headers/limits.h"
You need to configure Eclipse's indexer properly. If your project's type is "Makefile project" (so not any "managed" type, where you enter the compilation options/flags in Eclipse) you can do that as described below.
Go to your project's properties, then "C/C++ General" > "Preprocessor Include Paths, Macros etc." and switch to "Providers" tab. Uncheck everything other than:
CDT GCC Build Output Parser,
CDT Cross GCC Built-In Compiler Settings (depending on your project exact type, this should be some other type - for "Cross GCC" project, you select "... Cross GCC ..." checkbox).
Configure them as in below pictures:
In the first case you replace:
(gcc)|([gc]\+\+)|(clang)
with:
.*((gcc)|([gc]\+\+)|(clang))
This way Eclipse will know that all your lines starting with "... arm-none-eabi-gcc ..." or "... arm-none-eabi-g++ ..." are compiler invocations, so it will be able to parse the flags, including the include paths (-I flags). You can alter the options File/Folder/Project - depending on your configuration.
In the second case you replace what's in the textbox with something similar to:
arm-none-eabi-${COMMAND} ${FLAGS} -E -P -v -dD "${INPUTS}" -std=gnu++11 -std=gnu99 -mcpu=cortex-m4 -mthumb
And you need to specify proper flags, depending on your project. You enter only the flags that matter for the "built-in compiler settings" - these are -std, -mcpu, -mthumb, -mfpu, etc. As you see, you should enter flags for both C and C++ (if you use C++).
Of course if your compiler prefix is not "arm-none-eabi-" you should modify the options accordingly.
After that you should do a full rebuild of your project, so that Eclipse would be able to see ALL compilation commands for ALL files from your project. If your makefile hides the actual commands (for example it displays only "CC: some_file.c" instead of full command that is actually executed) this feature has to be disabled (you can alter the way make is invoked in project's properties under "C/C++ Build" in "Behavior" tab in "Build (incremental build)" textbox).
Sometimes it is also necessary to rebuild index manually, so right-click your project and go to "Index" > "Rebuild" (sometimes other options help too). Close all editors, maybe even close the project, and after reopening it should be OK.
After all these steps you should see a small "wrench" icons on your sources (or folders or whole project - depending on what you selected in the parser) - after you click such element with right button, select Properties and "C/C++ General" > "Preprocessor Include Paths, Macros etc." you should be able to see what Eclipse discovered there:

Configuring MSVC debugger in code::blocks

I am using code::blocks.
I set up the MSVC compiler(downloaded the MSVC Express 2010 Compiler and then added SDK directories).
The project does compile, however when I try to debug it ingores the breakpoints I set.
If I go Settings->Compiler->Toolchain Executables, the chosen Compiler is GDB/CDB : Default.
I guess the problem is gdb cannot debug msvc code. But how do I add a ne debugger?
In Settings->Debugger there is only one option of GDB/CDB compiler and I cannot add new one.
I tried adding additional directories, but it doesn't help.
So how do I make it work?
thanks
It's in Settings/Debugger and not in in Settings/Compiler/Toolchain Executables.
Got the same problem... I set path for cdb in code::blocks, ensured that the compiler added debug info, did everything I found on google (set Symbol Path to some weird stuff as described here: http://forums.codeblocks.org/index.php/topic,8454.msg63355.html#msg63355 and here: http://msdn.microsoft.com/en-us/library/windows/hardware/hh439323%28v=vs.85%29.aspx) - and still nothing. I didnt have any errors in debuger log, but it still wouldn't work. Finally - EUREKA: http://wiki.codeblocks.org/index.php?title=Debugging_with_Code::Blocks#Path_with_spaces
Breakpoints could not work if the path/folder you've placed your
project contains spaces or other special characters. To be safe use
English letters, digits and '_'.
After changing " " to "_" in directory names - everything works fine. And I lost only 5 hours for that...

How to determine which compiler was requested

My project uses SCons to manage the build process. I want to support multiple compilers, so I decided to use AddOption so the user can specify which compiler to use on the command line (with the default being whatever their current compiler is).
AddOption('--compiler', dest = 'compiler', type = 'string', action = 'store', default = DefaultEnvironment()['CXX'], help = 'Name of the compiler to use.')
I want to be able to have built-in compiler settings for various compilers (including things such as maximum warning levels for that particular compiler). This is what my first attempt at a solution currently looks like:
if is_compiler('g++'):
from build_scripts.gcc.std import cxx_std
from build_scripts.gcc.warnings import warnings, warnings_debug, warnings_optimized
from build_scripts.gcc.optimizations import optimizations, preprocessor_optimizations, linker_optimizations
elif is_compiler('clang++'):
from build_scripts.clang.std import cxx_std
from build_scripts.clang.warnings import warnings, warnings_debug, warnings_optimized
from build_scripts.clang.optimizations import optimizations, preprocessor_optimizations, linker_optimizations
However, I'm not sure what to make the is_compiler() function look like. My first thought was to directly compare the compiler name (such as 'clang++') against what the user passes in. However, this immediately failed when I tried to use scons --compiler=~/data/llvm-3.1-obj/Release+Asserts/bin/clang++.
So I thought I'd get a little smarter and use this function
cxx = GetOption('compiler')
def is_compiler (compiler):
return cxx[-len(compiler):] == compiler
This only looks at the end of the compiler string, so that it ignores directories. Unfortunately, 'clang++' ends in 'g++', so my compiler was seen to be g++ instead of clang++.
My next thought was to do a backward search and look for the first occurrence of a path separator ('\' or '/'), but then I realized that this won't work for people who have multiple compiler versions. Someone compiling with 'g++-4.7' will not register as being g++.
So, is there some simple way to determine which compiler was requested?
Currently, only g++ and clang++ are supported (and only their most recently released versions) due to their c++11 support, so a solution that only works for those two would be good enough for now. However, my ultimate goal is to support at least g++, clang++, icc, and msvc++ (once they support the required c++11 features), so more general solutions are preferred.
Compiler just are part of build process. Also you need linker tool and may be other additional programs. In Scons it's named - Tool. List of tools supported from box you can see in man page, search by statement: SCons supports the following tool specifications out of the box: ...
Tool set necessary scons environment variables, it's documented here.
Scons automatically detects compiler in OS and have some priority to choose one of them, of course autodetect will work properly if PATH variable set to necessary dirs. For example of you have msvc and mingw on windows, scons choose msvc tool. For force using tool use Tool('name')(env). For example:
env = Environment()
Tool('mingw')(env)
Now env force using mingw.
So, clang is one of tool which currently not supported from box by scons. You need to implement it, or set env vars such CC, CXX which using scons for generate build commands.
You could just simply use the Python os.path.basename() or os.path.split() functions, as specified here.
You could do what people suggested in the comments by splitting this question into 2 different issues, but I think it could be a good idea to be able to specify the path with the compiler, since you could have 2 versions of g++ installed, and if the user only specifies g++, they may not get the expected version.
There seems to be some confusion about what question is asked here.
For what I can see, this asks how to determine which compiler was chosen by default, so I'll answer that one.
From what I found out, the official way to check the compiler is to look at the construction variable TOOLS, which contains a list of all tools / programs that SCons decided / was told to use in the given construction environment.
env = Environment()
is_gcc = 'g++' in env['TOOLS']
is_clang = 'clangxx' in env['TOOLS']
TOOLS lists only the currently used tools even if SCons can find more of them.
E.g. if you have both GCC and Clang installed and SCons is able to find both, default TOOLS will still contain only GCC.
You can find the full list of predefined tools here.