C++ Static Code Analysis - Show header used in statement or line - c++

I'm searching for a tool to get the used header (if there is one/more) for every line/statment in my c++ code.
Example:
#include<iostream>
std::cout << "hallo";
The output i'd like to see:
line 2: std::cout uses "iostream"
I found this question, the tools there do most of the part, they show dependency per file.
Does anyone know such a tool or how to acomplish this with the tools given in the answers in the question above?
Goal: I'm checking code for the conformity to a standard which i have a list of allowed headers for. With the desired output I can create a metric saying something like: 60% of the code is using allowed headers, 15% is using other headers or something like that.

This is not completely what you want but you can use Eclipse CDT to know where std::cout is declared.
If you press F3 when cout is selected in Eclipse, you will jump to this line of code inside iostream header file on the system with gcc 7:
extern ostream cout; /// Linked to standard output

You can try CppDepend to get all the methods called by a specific one with the location of each method called.

Related

Fastest way to make console output "verbose" or not

I am making a small system and I want to be able to toggle "verbose" text output in the whole system.
I have made a file called globals.h:
namespace REBr{
extern bool console_verbose = false;
}
If this is true I want all my classes to print a message to the console when they are constructing, destructing, copying or doing pretty much anything.
For example:
window(string title="",int width=1280,int height=720):
Width(width),Height(height),title(title)
{
if(console_verbose){
std::cout<<"Generating window #"<<this->instanceCounter;
std::cout<<"-";
}
this->window=SDL_CreateWindow(title.c_str(),0,0,width,height,SDL_WINDOW_OPENGL);
if(console_verbose)
std::cout<<"-";
if(this->window)
{
this->glcontext = SDL_GL_CreateContext(window);
if(console_verbose)
std::cout<<".";
if(this->glcontext==NULL)
{
std::cout<<"FATAL ERROR IN REBr::WINDOW::CONSTR_OPENGLCONTEXT: "<<SDL_GetError()<<std::endl;
}
}
else std::cout<<"FATAL ERROR IN REBr::WINDOW::CONSTR_WINDOW: "<<SDL_GetError()<<std::endl;
if(console_verbose)
std::cout<<">done!"<<endl;
}
Now as you can see I have a lot of ifs in that constructor. And I REALLY dont want that since that will slow down my application. I need this to be as fast as possible without removing the "loading bar" (this helps me determine at which function the program stopped functioning).
What is the best/fastest way to accomplish this?
Everying in my system is under the namespace REBr
Some variants to achieve that:
Use some logger library. It is the best option as it gives you maximum flexibility and some useful experience ;) And you haven't to devise something. For example, look at Google GLOG.
Define some macro, allowing you to turn on/off all these logs by changing only the macro. But it isn't so easy to write such marco correctly.
Mark your conditional flag as constexpr. That way you may switch the flag and, depending on its value, compiler will optimise ifs in compiled program. But ifs will still be in code, so it looks kinda bulky.
Anyway, all these options require program recompilation. W/o recompilation it is impossible to achieve the maximum speed.
I often use a Logger class that supports debug levels. A call might look like:
logger->Log(debugLevel, "%s %s %d %d", timestamp, msg, value1, value2);
The Logger class supports multiple debug levels so that I can fine tune the debug output. This can be set at any time through the command line or with a debugger. The Log statement uses a variable length argument list much like printf.
Google's logging module is widely used in the industry and supports logging levels that you can set from the command line. For example (taken from their documentation)
VLOG(1) << "I'm printed when you run the program with --v=1 or higher";
VLOG(2) << "I'm printed when you run the program with --v=2 or higher";
You can find the code here https://github.com/google/glog and the documentation in the doc/ folder.

Beginner questions about vim

Question #1:
if I have a C++ code like this
#include <iostream>
using namesapce std;
int main() {
int a;
cin >> a;
cout << a << endl;
return 0;
}
I don't know if this is called (debugging, compiling, or building), but I just want to run this program inside gvim so I can give it the input and see the output, and see errors such as "missing ';' " or "missing '}' " (like what happens when I click F9 in "Code::Blocks").
exe file, and other things are not important for me.
Question #2:
if I have a C++ code that I write every time like this
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
How can I make vim insert this code every time I open a .cpp file with vim ?
I have Windows 7 32-bit and my .vimrc file is the default one that comes when I install vim.
Please be as detailed as possible.
Probably this is what you are looking for
Vi and Vim Autocommand: 3 Steps to Add Custom Header To Your File Automatically
Q1: You'll need to compile your C++ code first to "see errors such as "missing ';' " or "missing '}'". Then you can run your compiled EXE to determine if your input and output values work. In Visual Studio, hitting the play button (Debug) will do both.
Q2: vim has a set of events that occur that allow you to perform certain actions, like append text to a new file with an extension of .cpp. You would add some code to your .vimrc file to do this.
If you just want it on opening up use autocmd. You can do it like lipun4u said:
Vim autocommand auto add headers at start of file
Well I suggest getting this plugin: snipMate
snipMate.vim aims to be an unobtrusive, concise vim script that implements some of TextMate's snippets features in Vim. A snippet is a piece of often-typed text that you can insert into your document using a trigger word followed by a tab.
It has several features:
More than 1 language supported
Lots of premade snippets
Ability to make your own snippets
So this way you can have different headers for different programs, and just assign them to a hot key.

Doxygen warning: documented function not declared or defined

I'm trying to use Doxygen for the first time. On running Doxygen, I am presented with a large number of warnings of the following form:
<code>.cxx:<line number>: warning: documented function `<function>::<function>' was not declared or defined.
I'm not sure how to approach the problem. I'm working with a large C++ package and this type of warning is thrown up a few hundred times on running Doxygen.
Here's more specific information:
example warning:
Accept.cxx:14: warning: documented function `Accept::Accept' was not declared or defined.
corresponding example section of code:
#include "Analysis/Accept.h"
#include "Analysis/Cutflow.h"
#include "GlaNtp/GlaUtil/Steer/Steer.h"
#include <iostream>
Accept::Accept(unsigned int cutmask, unsigned int invertword, StringIntMap* CutTypeMap, Cutflow* analysis_cutflow): m_cutmask(cutmask), m_invertword(invertword),
m_cutword(0),m_cutword_set(false), m_CutTypeMap(CutTypeMap),
m_analysis_cutflow(analysis_cutflow){
// this is constructor
InitBitOrder();
}
Accept::~Accept(){}
void Accept::setCutWord(const unsigned int &cutword){
m_cutword_set = true;
m_cutword = cutword;
}
bool Accept::didBitPass(){
//std::cout << "Rick Evnt Pass: " << rickTestCutWord() << std::endl;
return testCutWord();
}
void Accept::InitBitOrder(){
Steer* bitorsteer=new Steer();
std::string configfile="ConFigFiles/ApplyBits/BitOrderConfigurationFile.txt";
if(!bitorsteer->ReadFile(configfile)){
std::cout << "Fatal ERROR: Failed to read Bit Order configuration steering file: " << configfile << std::endl;
delete bitorsteer;
bitorsteer=0;
exit(1);
}
m_bitOrderMap = new StringIntMap("BitOrder", bitorsteer);// bit order
delete bitorsteer;
}
I would appreciate any assistance you might have in pointing me in the right direction.
Preemptive thanks
My guess is that Doxygen is not parsing the Analysis/Accept.h header file, so it's not seeing the Analysis class declaration. In the output log, check that Analysis/Accept.h is indeed being processed.
To ensure that Doxygen parses the Analysis directory, you may have to add additional source directories in Expert->Input (in the Doxygen GUI frontend), and/or enable the Recursive option. Perhaps you have to specify a source directory one level above the one you've currently specified.
I was having the same problem, and followed the advice given by Emile Cormier. In my case the relevant header file was indeed not being parsed. This was because I have a c++ header file with the extension .h. I originally had the following in my Doxygen.in file:
EXTENSION_MAPPING = .h=C++
Looking at the output carefully, I noticed the statement: "Adding custom extension mapping: ..h will be treated as language c++", indicating an extra ".". Removing the period from the relevant line fixed my problem.
FWIW, I had another case that triggered such a warning: having a typedef done in two different places. This is OK wrt C++, but causes doxygen (1.8.7) to issue this very warning. Reordering to have a single definition fixed it.

C++: Unable to resolve identifier cout, Netbeans, Ubuntu

I am using C++ on Netbeans 7.1 on Ubuntu 11.04. For some reason, the following code results in the error message "Unable to resolve identifier cout".
#include <iostream>
using namespace std;
int main()
{
std::cout << "Hello,world!\n";
return 0;
}
Any help resolving this problem would be greatly appreciated.
The solution for your problem is at least strange ;)
Once iostream header is added, one has to reparse code. Click right on a project, go to code assistance and click to reparse project. Worked for me.
I was using netbeans for mac.
check whether iostream is really getting included;
i have tried your code on my machine using eclipse cdt it worked fine.so, please check the
includes.
What sort of file is this in? Is it a .h file, or .hpp file? I had this same issue. Netbeans can be ridiculous sometimes with C++. For me, I changed #include <iostream> to #include<iostream.h>
This may seem too simple, but...
In my NetBeans installation, when I go to create a new project, specify C/C++, it brings up a dialog box prompting for "Project Name:", location, folder, makefile name, and then...
a check box for "Create Main File", an edit box with "main" filled in, and to the right of that is a drop down list that reads "C". If you hit Finish, this will create "main.c" (C, but NOT a C++ file). Instead, in the drop down list, select "C++". Then the IDE creates main.cpp, which will be compiled with g++ and will find those includes and functions.
There is a difference between std::cout and cout. You don't currently have std::cout defined in your file. std::cout is a c standard out. In C++ we only need cout to work with iostream.
If you must use a standard c out then do the following:
Add this to the top under iostream
#include <iostream> //Input output stream in C++
#include <cstdlib> //Stands for c standard library
using namespace std;
Your code will now work because:
This change defines std::cout and std::cin among other things. (standard in, standard out respectively.)
However, I'd recommend this alternative if you don't need standard in outs:
Replace std::cout with cout, because cout is defined in iostream in C++. Your program would have worked without the std:: portion of your cin cout commands because you originally included iostream.
Try taking out the using namespace std; - it's generally considered bad form anyway :-)
I'm not sure that will fix the problem but most people either use the namespace or fully qualify things like std::cout. I've never seen code that does both.
The other thing to check is that the iostream header actually is being bought in. In other words, are there any errors on that line. A lot of problems (at least in the Windows world, so it may not necessarily apply to you) seem to be due to faulty path setup in NetBeans.
Hey look at your Output Debug. You may see "no permission". After I changed the file permission of "/YourProjekt/dist/Debug/GNU-Linux/file" to runable and everyone can read and write the error disappeared. (BTW: I had the bug because I was on a NTFS System with my Projekt, it have to be ext partition)
Hope I can help you with that.
Try taking out the std:: next to cout

Segmentation fault when different input is given

I do some image processing work in C++. For this i use CImg.h library which i feel is good for my work.
Here is small piece of code written by me which just reads an image and displays it.
#include "../CImg.h"
#include "iostream"
using namespace std;
using namespace cimg_library;
int main(int argc,char**argv)
{
CImg<unsigned char> img(argv[1]);
img.display();
return 0;
}
When i give lena.pgm as input this code it displays the image. Where as if i give some other image, for example ddnl.pgm which i present in the same directory i get "Segmentation Fault".
When i ran the code using gdb i get the output as follows:
Program received signal SIGSEGV, Segmentation fault.
0x009823a3 in strlen () from /lib/libc.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.9-2.i686 libX11-1.1.4-5.fc10.i386 libXau-1.0.4-1.fc10.i386 libXdmcp-1.0.2-6.fc10.i386 libgcc-4.3.2-7.i386 libstdc++-4.3.2-7.i386 libxcb-1.1.91-5.fc10.i386
Can some one please tell me what the problem is? and how to solve it.
Thank you all
Segfault comes when you are trying to access memrory which you are not allowed to access.
So please check that out in the code.
The code itself looks just fine. I can suggest some ways to go ahead with debugging -
Try removing the display() call. Does the problem still occur? (I'd assume it does).
Try finding out where in the CImg code is the strlen() that causes the segmentation fault (by using a debugger). This may give additional hints.
If it is in the PGM file processing, maybe the provided PGM file is invalid in some way, and the library doesn't do error detection - try opening it in some other viewer, and saving it again (as PGM). If the new one works, comparing the two may reveal something.
Once you have more information, more can be said.
EDIT -
Looking at the extra information you provided, and consulting the code itself, it appears that CImg is failing when trying to check what kind of file you are opening.
The relevant line of code is -
if (!cimg::strcmp(ftype,"pnm")) load_pnm(filename);
This is the first time 'ftype' is used, which brings me to the conclusion that it has an invalid value.
'ftype' is being given a value just a few lines above -
const char *const ftype = cimg::file_type(0,filename);
The file_type() function itself tries to guess what file to open based on its header, probably because opening it based on the extension - failed. There is only one sane way for it to return an invalid value, which would later cause strcmp() to fail - when it fails to identify the file as anything it is familiar with, it returns NULL (0, actually).
So, I reiterate my suggestion that you try to verify that this is indeed a valid file. I can't point you at any tools that are capable of opening/saving PGM files, but I'm guessing a simple Google search would help. Try to open the file and re-save it as PGM.
Another "fun to track down" cause of segmentation faults is compilier mismatches between libraries - this is especially prevalent when using C++ libraries.
Things to check are:
Are you compiling with the same compiler as was used to compile the CImg library?
Are you using the same compiler flags?
Were there any defines that were set when compiling the library that you're not setting now?
Each of these has bitten me in subtle ways before.