I am writing a program in C++. When I use the strlen function, it is underlined by a red line. Although the project is built without errors. This is how I use this function. (By the way, strcpy is also underlined).
Exception::Exception(int _Line, char* _File, char* _Func, char* _Desc)
{
Line = _Line;
int size = strlen(_File) + 1;
File = new char[size];
strcpy(File, _File);
Func = new char[size];
strcpy(Func, _Func);
Desc = new char[size];
strcpy(Desc, _Desc);
}
And I declared <cstring> library at the beginning of the file. Please tell me how I can fix this?
As you can read up in the documentation for strlen(), strlen() is defined in string.h and the C++ counterpart std::strlen() is defined in cstring.
So to get rid of the error squiggles try adding one of the aforementioned headers.
#include <cstring>
...
std::strlen()
The system that underlines the code in the VS editor, called IntelliSense, does not use the same code as the compiler itself (or at least did not a few years ago when I used it last time). Sometimes it gets confused.
Try std::strlen instead, reorganizing the code, the includes, or something else.
I'm getting the following message trying to compile some simple code: MSB6006 "CL.exe" exited with code 2.
I'm trying to learn C++. I know some C. I understand the two are completely different languages. I include both tags because I get different results depending on how I try to compile the code.
For my own education, I'm trying to write a lexer. Mainly the problem seems to be with this function:
word scan(char** source)
{
word w;
w.lexeme[0] = '\0';
return w;
}
I get the same problem as this one MSB6006: "CL.exe" exited with code 2 but the answer doesn't apply in my case. I saw this question error MSB6006: "CL.exe" exited with code 2 which pointed to this question on the MSDN site They seem to indicate that small problems can cause this error code.
I have two files. One is a "driver" and the other is the lexer code. But I get the exact same results if I include everything in one file.
Here is the code for the driver:
#include "pch.h"
#include "Cl2aDLL.h"
void Cl2a(char argv1[], char argv2[])
{
char** source = NULL;
scan(source);
}
Here is the code for the header. I got the technique somewhere from a MSFT website:
#pragma once
#ifndef CL2ADLL__H__
#define CL2ADLL__H__
typedef struct {
char* lexeme;
}word;
#ifdef __cplusplus
extern "C" {
#endif
#ifdef CL2ADLL_EXPORTS
#define CL2ADLL_API __declspec(dllexport)
#else
#define CL2ADLL_API __declspec(dllimport)
#endif
CL2ADLL_API void Cl2a(char argv1[], char argv2[]);
word scan(char** source);
#ifdef __cplusplus
}
#endif
#endif // ! CL2ADLL__H__
Here is the code for the lexer:
// Error MSB6006 "CL.exe" exited with code 2.
#include "pch.h"
#include "Cl2aDLL.h"
/*
// when I comment out the following lines, it compiles and runs okay
word scan(char** source)
{
word w;
w.lexeme[0] = '\0';
return w;
}
*/
// if I only have the following, I get compile error if .cpp
word scan(char** source)
{
}
The strange thing is that if I compile as C code it compiles and runs okay. But if I try to compile as C++ I get the error message. If I uncomment out the first version of the scanner, I get the error message compiling as C or C++ either one.
Does anyone know of a change that can remove this error message?
Sorry for the long question, but I'm trying to give as clear a definition of the problem as I can. Because I can't figure out what could be wrong. TIA.
Update: I'm using VS 2019 Community Edition 16.1.1
Update 2: I got the same results with version 16.1.2. But trying the code in VS2017 Community Edition 15.9.12 showed the problem, as shown below.
Also I should have explained that all the above code was in a .dll file. The .dll code was run from a simple console application as follows:
#include "..\CL2aDLL\CL2aDLL.h"
int main(int argc, char* argv[])
{
char parm1[1 + 1] = "";
char parm2[1 + 1] = "";
if (argc == 1) {
Cl2aDLL(parm1, parm2);
}
else {
Cl2aDLL(argv[1], argv[2]);
}
return 0;
}
I've done some additional research.
Running the code in VS Community Edition 15.9.12 showed that the line w.lexeme[0] = '\0'; was trying to use an uninitialized pointer.
The corrected function is:
word scan(char** source)
{
word w;
w.lexeme = (char*)malloc(1); // <-- line added
w.lexeme[0] = '\0';
return w;
}
This compiles and runs okay.
However that still doesn't explain why this code gives the MSB6006 error:
word scan(char** source)
{
}
And this only happens when compiling as C++. It compiles and runs okay if compiling as C.
Update: I reported the problem to MSFT but it doesn't look liked they fixed the problem yet.
I'm trying to add a simple diagnostic output to a C++ UWP shared project akin to System.Diagnostics.Debug.WriteLine in C#. Following the documentation for OutputDebugString here and this solution here I've tried this:
char buf[1024];
sprintf(buf, "frequency = %f", (float)result);
OutputDebugString(buf);
but I get the compiler error
argument of type "char*" is incompatible with parameter of type "LPCWSTR"
How do I fix this?
A colleague advised me to add
#include "strsafe.h"
after any pre-compiled headers and then use this code instead
TCHAR buf[1024];
size_t cbDest = 1024 * sizeof(TCHAR);
StringCbPrintf(buf, cbDest, TEXT("frequency = %f"), (float)result);
OutputDebugString(buf);
I also needed to remember to swap the debugger to handle mixed code:
Here is what I use most of the time (notice the "L"):
#include <Windows.h>
OutputDebugString(L"Sarah Connor ?\n");
The simplest way of defining my problem is that I'm trying to implement a mechanism that would check whether the same string had already been used (or a pair (number, string)). I would like this mechanism to be implemented in a smart way using C preprocessor. I would also like that this mechanism gave me compile errors when there is a conflict or run-time errors in Debug mode (by checking assertions). We don't want the developer to make a mistake when adding a message, as every message should be unique. I know that it could be done by calculating a hash or for example crc/md5 but this mechanism would be conflict-vulnerable which I need to avoid. It is crucial that every message can be used only once.
Example behaviour of this mechanism:
addMessage(1, "Message1") //OK
addMessage(2, "Message2") //OK
.
.
.
addMessage(N, "MessageN") //OK
addMessage(2, "Message2") //Compile error, Message2 has already been used
Alternative behaviour (when Debugging code):
addMessage(1, "Message1") //OK
addMessage(2, "Message2") //OK
.
.
.
addMessage(N, "MessageN") //OK
addMessage(2, "Message2") //Assertion failed, because Message2 has already been used
The preferred way of doing it would be smart usage of #define and #undef directives. In general the preprocessor should be used in a smart way (I am not sure if this is possible) maybe it can be achieved by appropriate combinations of macros? Any C preprocessor hacker that could help me solve this problem?
//EDIT: I need those messages to be unique globally, not only inside one code block (like function of if-statement).
//EDIT2: The best description of the problem would be that I have 100 different source files and I would like to check with a preprocessor (or possibly other mechanism other than parsing source files with a script at a start of the compilation every-time, which would be very time-consuming and would add another stage to an enough complicated project) if a string (or a preprocessor definition) was used more than one time. I still have no idea how to do it (I know it may not be possible at all but I hope it actually is).
This will give an error on duplicate strings:
constexpr bool isequal(char const *one, char const *two) {
return (*one && *two) ? (*one == *two && isequal(one + 1, two + 1))
: (!*one && !*two);
}
constexpr bool isunique(const char *test, const char* const* list)
{
return *list == 0 || !isequal(test, *list) && isunique(test, list + 1);
}
constexpr int no_duplicates(const char* const* list, int idx)
{
return *list == 0 ? -1 : (isunique(*list, list + 1) ? no_duplicates(list + 1, idx + 1) : idx);
}
template <int V1, int V2> struct assert_equality
{
static const char not_equal_warning = V1 + V2 + 1000;
};
template <int V> struct assert_equality<V, V>
{
static const bool not_equal_warning = 0;
};
constexpr const char* l[] = {"aa", "bb", "aa", 0};
static_assert(assert_equality<no_duplicates(l, 0), -1>::not_equal_warning == 0, "duplicates found");
Output from g++:
g++ -std=c++11 unique.cpp
unique.cpp: In instantiation of ‘const char assert_equality<0, -1>::not_equal_warning’:
unique.cpp:29:57: required from here
unique.cpp:20:53: warning: overflow in implicit constant conversion [-Woverflow]
unique.cpp:29:1: error: static assertion failed: duplicates found
The first template parameter (in this case 0) to 'assert_equality' tells you the fist position of a duplicate string.
I am not sure that it is easily doable using the standard C++ preprocessor (I guess that it is not). You might use some other preprocessor (e.g. GPP)
You could make it the other way: generate some X-macro "header" file from some other source (using e.g. a tiny awk script, which would verify the unicity). Then customize your build (e.g. add some rules to your Makefile) to run that generating script to produce the header file.
Alternatively, if you insist that processing being done inside the compiler, and if your compiler is a recent GCC, consider customizing GCC with MELT (e.g. by adding appropriate builtins or pragmas doing the job).
In the previous century, I hacked a small Emacs function to do a similar job (uniquely numbering error messages) within the emacs editor (renumbering some #define-s before saving the C file).
I am going to assume that something like this will work:
addMessage(1, "Message1")
addMessage(2, "Message1")
Or:
addMessage(1, "Message") /* transforms into "Message_1" */
addMessage(2, "Message_1") /* transforms into "Message_1_2" */
Because the C preprocessor expands tokens lazily and prohibits defining a macro from within another macro, it is impossible to save the results of executing one macro so that another macro can make use of it.
On the other hand, it is definitely possible to force uniqueness of symbols:
#define addMessage(N, MSG) const char *_error_message_##N (void) { return MSG; }
Or:
#define addMessage(N, MSG) const char *_error_message_##N (void) { return MSG "_" #N; }
Because during the link step, duplicate symbols with the name _error_message_NUMBER will trigger an error. And because it is a function, it cannot be used inside of another function without triggering an error.
Assuming your compiler is still not C++11 compliant as you have not tagged appropiately. I am also assuming that you are not particular about the Error Message, its just that you want it to work. In which case, the following Macro Based Solution might work for you
#include <iostream>
#include <string>
#define ADD_MESSAGE(N, MSG) \
char * MSG; \
addMessage(N, #MSG);
void addMessage(int n, std::string msg)
{
std::cout << msg << std::endl;
}
int main() {
ADD_MESSAGE(1, Message1); //OK
ADD_MESSAGE(2, Message2); //OK
ADD_MESSAGE(3, MessageN); //OK
ADD_MESSAGE(4, Message2); //Compile error, Message2 has already been used
};
Compile Output
prog.cpp: In function ‘int main()’:
prog.cpp:17:17: error: redeclaration of ‘char* Message2’
ADD_MESSAGE(4, Message2); //Compile error, Message2 has already been used
^
prog.cpp:4:8: note: in definition of macro ‘ADD_MESSAGE’
char * MSG; \
^
prog.cpp:15:17: error: ‘char* Message2’ previously declared here
ADD_MESSAGE(2, Message2); //OK
^
prog.cpp:4:8: note: in definition of macro ‘ADD_MESSAGE’
char * MSG; \
^
If you don't care about large amounts of useless boiler plate then here's one that's entirely the preprocessor, so no worries about scope, and then checks that they are unique at program startup.
In a file:
#ifndef ERROR1
#define ERROR1 "1"
#endif
#ifndef ERROR2
#define ERROR2 "2"
#endif
...
#ifndef ERROR255
#define ERROR255 "255"
#endif
#include <assert.h>
#include <set>
#include <string>
class CheckUnique {
CheckUnique() {
std::set<std::string> s;
static const char *messages = {
#if HAVE_BOOST
# include <boost/preprocessor.hpp>
# define BOOST_PP_LOCAL_LIMITS (1, 254)
# define BOOST_PP_LOCAL_MACRO(N) ERROR ## N,
# include BOOST_PP_LOCAL_ITERATE()
#else // HAVE_BOOST
ERROR1,
ERROR2,
...
#endif // HAVE_BOOST
ERROR255
};
for (int i = 0; i < sizeof messages / sizeof *messages; i++) {
if (s.count(messages[i]))
assert(! "I found two error messages that were the same");
else
s.insert(messages[i]);
}
}
};
static CheckUnique check;
This file can then be #included at the end of each source file, or you can place it into a file of its own and include every single file that has a #define ERROR line in it. That way, as soon as the operating system loads the program, the constructor for check will run and throw the exception.
This also requires you to have access to the Boost.Preprocessor library (and it's header only so it's pretty easy to set up). Although if you can't use that, then you can just hard code the error macros as I have shown with the #if HAVE_BOOST block.
Most of the boiler plate here is pretty simple, so if you generated it with a program (like some sort of portable script) then it would make your life far easier, but it can still be done all in one shot.
I have an issue with GetCurrentDirectory(), and i don't really understand why. The thing i don't understand is that it works for XP but not for Seven (or at least on my computer). There is my code:
char dir_name[1024]; // as a global variable
int get_files() {
// ...
DWORD dwRet;
dwRet = GetCurrentDirectory(MAX_PATH, dir_name);
printf("%s\n",dir_name);
printf("%d\n",dwRet);
//...
}
This code will return:
printf("%s\n",dir_name); -> return "c"
printf("%d\n",dwRet); -> 42 (which is the right length of the string that should be returned)
I don't understand why dir_name only takes the value "c".
I think, the result is Unicode in Windows Seven! and after each ascii character of this function there is zero. And you are printing it by printf. You should use wide-char functions in your program. Like wprintf.
Try below code: (Tested in Visual Studio 2008 + Windows 7)
#include <stdio.h>
#include <windows.h>
#include <wchar.h>
WCHAR dir_name[1024]; // as a global variable
int get_files()
{
// ...
DWORD dwRet;
dwRet = GetCurrentDirectory(MAX_PATH, dir_name);
wprintf(L"%s\n", dir_name);
printf("%d\n", dwRet);
//...
return 0;
}
Im not sure, but could it be GetCurrentDirectory() returns 2-byte chars under win7?
In such case you'll be getting a 0 in each second bytes of the char array returned.
So you should use a wide-char aware version of the printf() function such as wprintf().
Also I wonder whether the compiler wouldn't have warned you about something being wrong regarding types.
what compiler are you using? Under Visual C++ 2005, GetCurrentDirectory is a macro that resolves to GetCurrentDirectoryW if UNICODE macro is defined and to GetCurrentDirectoryA otherwise. Do you have UNICODE defined by any chance?