Using C++ strtk results in an xutility error C4996 - c++

So I'm working on a little project to get into C++, and part of that is reading and writing data to a file. I've chosen the simplest route I know of, which is turning the various attributes of the object into a string of integers. To be clear, I'm working with an object "Day" which has various attributes about my day (minutes slept, minutes exercised, etc.) I currently have the following snippet of code:
string Day::writeAsData()
{
// Writes the day as a condensed machine-readable format:
// {rawTime,busyMinutes,sleepMinutes,productivity,enjoyment,fatigue,weight,calories}
// e.g. {1444316982,645,360,7,4,5,180,0}
string dataString = "{"
+ to_string(rawTime) + ","
+ to_string(busyMinutes) + ","
+ to_string(sleepMinutes) + ","
+ to_string(productivity) + ","
+ to_string(enjoyment) + ","
+ to_string(fatigue) + ","
+ to_string(weight) + ","
+ to_string(calories)
+ "}";
return dataString;
}
to write the data in a clear machine-readable format. I'm working on a companion function to get the data out of a string and set the values of the Day object appropriately. I found the C++ String Toolkit Library, and I want to use its parse() function. However, adding
#include "strtk.hpp"
to my list of includes ends up throwing a wrench in the build. Taking that line out, I get a clean and successful build. However, adding that line results in
Error C4996 'std::_Fill_n': Function call with parameters that may be unsafe - this
call relies on the caller to check that the passed values are correct. To disable this
warning, use -D_SCL_SECURE_NO_WARNINGS.
in line 2811 of xutility. I don't use std::Fill_n anywhere in my code.
So far, I've found that the String Toolkit uses the Boost libraries, which I have placed in my include directory. I tried to add
#define D_SCL_SECURE_NO_WARNINGS 1
to my Day.cpp file and my Day.h file, but neither have done anything. I can't add it to xutility because the file is read only. How can I either disable the warning or fix the issue?

First, your #define is not correct, it should be:
#define _SCL_SECURE_NO_WARNINGS
More details here:
MSDN: _SCL_SECURE_NO_WARNINGS
And here:
What does "use -D_SCL_SECURE_NO_WARNINGS" mean?
Second, if you are using visual studio (and I assume you are) you can define _SCL_SECURE_NO_WARNINGS for your whole project using the project settings under Preprocessor Definitions

Related

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

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.

How can I find out the date of when my source code was compiled?

Is it possible to store and display the date of when my project was compiled?
I'd like to print this date when the program starts in order to know which version is used. Currently, I am doing this by hand, which is rather cumbersome.
I am using Visual Studio 2010.
C++ specifies that there's a special preprocessor macro called __DATE__ that is a string literal of when the compilation happened. There's also a corresponding __TIME__ macro.
You can use at such:
const std::string compilation_date = __DATE__;
const std::string compilation_time = __TIME__;
...
std::cout << "This source file was compiled on date " << compilation_date
<< " and at the time " << compilation_time << '\n';
You can use the __DATE__ and __TIME__ macros - see "Predefined macros" here.
As a sample, something like this:
#include <iostream>
int main()
{
using namespace std;
cout << "Compiled on: " << __DATE__ << endl;
cout << "Compiled at: " << __TIME__ << endl;
}
You would modify the messages and use according to your needs.
You could even look to building it up into a larger macro or named variable.
#include <iostream>
const char* const COMPILED = __DATE__ " # " __TIME__;
int main()
{
using namespace std;
cout << "Compiled: " << COMPILED << endl;
}
If the "version" information is tied to a source control location or data (such as a commit number), it may also be an idea to include that data in the build via a build step or command line define of some sort. You should also consider the effect of incremental builds on the date and time. I'm assuming the "release" builds are not incremental based, or if so, there is "touch" on the file containing the date and time data.
There are TWO parts to this. The first one (already mentioned in the answers) is to use __DATE__. Unfortunately, this will just tell you the date of compilation for that Translation Unit. If you want the date of the last Visual Studio Build, you need to force a rebuild of the Translation Unit containing __DATE__
One simple solution to this is to always update the file time of that Translation Unit. Say you want Joachim's solution, then you create a separate builddate.cpp file with
const std::string compilation_date = __DATE__;
const std::string compilation_time = __TIME__;
In the post build step, call copy /b builddate.cpp+,,. This means that after every build, the builddate.cpp file becomes newer than the executable and will be recompiled on the next build.
On Linux you'd use touch for this.
Your question shows that you are not using version control system. You should, there are no excuses like "my project too small I'll do it later when will work on something bigger" or "it is too complex". VCS is must use for every developer, when you start to use it you will not imagine how you lived before without it. So when you start to use VCS your question will be "how to put comit or tag version into source?" For example on svn you can use:
const char *version = "$Id:$";
and svn will change it to current commit version. For other VCS systems solution could be different but close, as this problem is very common.
There is a macro called
__DATE__
which resolves to something like "Apr 1 2015". One can just use that. It is a standard predefined macro.
__ DATE __ :
This macro expands to a string constant that describes the date on which the preprocessor is being run. The string constant contains eleven characters and looks like "Feb 12 1996". If the day of the month is less than 10, it is padded with a space on the left. If GCC cannot determine the current date, it will emit a warning message (once per compilation) and DATE will expand to "??? ?? ????". https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html
However, this solution lacks formatting. Of course, you can parse it, but maybe there is an easier, more C++ like solution.

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.

Compile a program with local file embedded as a string variable?

Question should say it all.
Let's say there's a local file "mydefaultvalues.txt", separated from the main project. In the main project I want to have something like this:
char * defaultvalues = " ... "; // here should be the contents of mydefaultvalues.txt
And let the compiler swap " ... " with the actual contents of mydefaultvalues.txt. Can this be done? Is there like a compiler directive or something?
Not exactly, but you could do something like this:
defaults.h:
#define DEFAULT_VALUES "something something something"
code.c:
#include "defaults.h"
char *defaultvalues = DEFAULT_VALUES;
Where defaults.h could be generated, or otherwise created however you were planning to do it. The pre-processor can only do so much. Making your files in a form that it will understand will make things much easier.
The trick I did, on Linux, was to have in the Makefile this line:
defaultvalues.h: defaultvalues.txt
xxd -i defaultvalues.txt > defaultvalues.h
Then you could include:
#include "defaultvalues.h"
There is defined both unsigned char defaultvalues_txt[]; with the contents of the file, and unsigned int defaultvalues_txt_len; with the size of the file.
Note that defaultvalues_txt is not null-terminated, thus, not considered a C string. But since you also have the size, this should not be a problem.
EDIT:
A small variation would allow me to have a null-terminated string:
echo "char defaultvalues[] = { " `xxd -i < defaultvalues.txt` ", 0x00 };" > defaultvalues.h
Obviously will not work very well if the null character is present inside the file defaultvalues.txt, but that won't happen if it is plain text.
One way to achieve compile-time trickery like this is to write a simple script in some interpreted programming language(e.g. Python, Ruby or Perl will do great) which does a simple search and replace. Then just run the script before compiling.
Define your own #pramga XYZ directive which the script looks for and replaces it with the code that declares the variable with file contents in a string.
char * defaultvalues = ...
where ... contains the text string read from the given text file. Be sure to compensate for line length, new lines, string formatting characters and other special characters.
Edit: lvella beat me to it with far superior approach - embrace the tools your environment supplies you. In this case a tool which does string search and replace and feed a file to it.
Late answer I know but I don't think any of the current answers address what the OP is trying to accomplish although zxcdw came really close.
All any 7 year old has to do is load your program into a hex editor and hit CTRL-S. If the text is in your executable code (or vicinity) or application resource they can find it and edit it.
If you want to prevent the general public from changing a resource or static data just encrypt it, stuff it in a resource then decrypt it at runtime. Try DES for something small to start with.

Is there a TRACE statement for basic win32 C++?

In MFC C++ (Visual Studio 6) I am used to using the TRACE macro for debugging. Is there an equivalent statement for plain win32?
_RPTn works great, though not quite as convenient. Here is some code that recreates the MFC TRACE statement as a function allowing variable number of arguments. Also adds TraceEx macro which prepends source file and line number so you can click back to the location of the statement.
Update: The original code on CodeGuru wouldn't compile for me in Release mode so I changed the way that TRACE statements are removed for Release mode. Here is my full source that I put into Trace.h. Thanks to Thomas Rizos for the original:
// TRACE macro for win32
#ifndef __TRACE_H__850CE873
#define __TRACE_H__850CE873
#include <crtdbg.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#ifdef _DEBUG
#define TRACEMAXSTRING 1024
char szBuffer[TRACEMAXSTRING];
inline void TRACE(const char* format,...)
{
va_list args;
va_start(args,format);
int nBuf;
nBuf = _vsnprintf(szBuffer,
TRACEMAXSTRING,
format,
args);
va_end(args);
_RPT0(_CRT_WARN,szBuffer);
}
#define TRACEF _snprintf(szBuffer,TRACEMAXSTRING,"%s(%d): ", \
&strrchr(__FILE__,'\\')[1],__LINE__); \
_RPT0(_CRT_WARN,szBuffer); \
TRACE
#else
// Remove for release mode
#define TRACE ((void)0)
#define TRACEF ((void)0)
#endif
#endif // __TRACE_H__850CE873
From the msdn docs, Macros for Reporting:
You can use the _RPTn, and _RPTFn macros, defined in CRTDBG.H, to replace the use of printf statements for debugging. These macros automatically disappear in your release build when _DEBUG is not defined, so there is no need to enclose them in #ifdefs.
There is also OutputDebugString. However that will not be removed when compiling release.
Trace macros that provide messages with source code link, run-time callstack information, and function prototype information with parameter values:
Extended Trace: Trace macros for Win32
I just use something like this (from memory, not tested at all...)
#define TRACE(msg) {\
std::ostringstream ss; \
ss << msg << "\n"; \
OutputDebugString(msg.str()); \
}
And then I can write things like :-
TRACE("MyClass::MyFunction returned " << value << " with data=" << some.data);
You can wrap that in some #ifdefs to remove it in release builds easily enough.
I found that using the _RPT() macro will also work with a C source file in Visual Studio 2005. This article Debugging with Visual Studio 2005/2008: Logging and Tracing provides an overview of TRACE, _RPT, and other logging type macros.
I generate a line for a log file called the ASSRTLOG which contains logs and when writing the log to the file, I also do the following source code line:
_RPT1(_CRT_WARN, "ASSRTLOG: %s", szLog1);
This line puts the same log that is going into the log file into the output window of the Visual Studio 2005 IDE.
You might be interested in the mechanics behind the approach we are using for logging. We have a function PifLogAbort() which accepts a series of arguments that are then used to generate a log. These arguments include the name of the file where the log is being generated along with the line number. The macro looks like this:
#define NHPOS_ASSERT_TEXT(x, txt) if (!(x)) { PifLogAbort( (UCHAR *) #x , (UCHAR *) __FILE__ , (UCHAR *) txt , __LINE__ );}
and the function prototype for PifLogAbort() look like this:
PifLogNoAbort(UCHAR *lpCondition, UCHAR *lpFilename, UCHAR *lpFunctionname, ULONG ulLineNo)
and to use the macro we will insert a line like this:
NHPOS_ASSERT_TEXT(sBRetCode >= 0, "CliEtkTimeIn(): EtkTimeIn() returned error");
What this macro will do is that if the return code is less than 0 (the assertion fails), a log will be generated with the provided text. The log includes the condition that generated the log along with file name and line number.
The function PifLogAbort() generates logs with a specified length and treats the output file as a circular buffer. The logs have a time and date stamp as well.
In those cases where we want to generate the descriptive text dynamically at run time, perhaps to provide the actual error code value, we use the sprintf() function with a buffer as in the following code sequence:
if (sErrorSave != STUB_BM_DOWN) {
char xBuff[128];
sprintf(xBuff, "CstSendBMasterFH: CstComReadStatus() - 0x%x, sError = %d", usCstComReadStatus, CliMsg.sError);
NHPOS_ASSERT_TEXT((sErrorSave == STUB_BM_DOWN), xBuff);
}
If we want the logs to not be generated, all we need to do is to go to the single header file where the macro is defined and define it to be nothing then recompile. However we have found that these logs can be very valuable when investigating field issues and are especially useful during integration testing.
Windows Events are a potential replacement for TRACE macros, depending on your particular scenario. The code gets compiled into both Debug and Release configurations. Event tracing can then be dynamically enabled and disabled, displayed in real-time, or dumped on a client's machine for later diagnosis. The traces can be correlated with trace information gathered from other parts of the OS as well.
If you merely need to dump information whenever code reaches certain checkpoints, together with variable content, stack traces, or caller names, Visual Studio's Tracepoints are a non-intrusive option to do so.