Tag Archives: c++

How to Solve Visual Studio C4996 Error

Follow the path VisualStudio\Common7\IDE\VC to find the folder VCProjectItems:

Right click to grant access permission -> Specific user

Click “share”

Enter the folder VCProjectsItems and open the file newc++file.cpp with Notepad. Paste the following into the file and save:

#define _CRT_SECURE_NO_WARNINGS 1

Right-click the folder VCProjectItems and click Properties -> Share -> Advanced sharing, click “share this folder” to uncheck it, and click “apply” and “OK”.

This will solve the problem. Create a new C/C + + file in vs. you can see the following code on the first line:

#define _CRT_SECURE_NO_WARNINGS 1

​​​​​​​

In this way, no error will be reported when using functions such as scanf(), printf().

[Solved] C++ reason ncnn model error: Segmentation fault (core dumped)

The reasoning code is as follows:

#include "net.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <stdio.h>
#include <vector>
#include <opencv2/opencv.hpp>

using namespace std;

void pretty_print(const ncnn::Mat& m)
{
    for (int q=0; q<m.c; q++)
    {
        const float* ptr = m.channel(q);
        for (int y=0; y<m.h; y++)
        {
            for (int x=0; x<m.w; x++)
            {
                printf("%f ", ptr[x]);
            }
            ptr += m.w;
            printf("\n");
        }
        printf("------------------------\n");
    }
}
//main fuction
int main(){
    string img_path = "person1.jpeg";
    cv::Mat img = cv::imread(img_path, cv::IMREAD_COLOR);
    cv::Mat img2;
    int input_width = 512;//Input size specified when going onnx
    int input_height = 512;
    
    cv::resize(img, img2, cv::Size(input_width, input_height));
  

    // Load the converted and quantized alexnet network
    ncnn::Net net;
    // net.opt.num_threads=1;
    net.load_param("cps_simplif.param");
    net.load_model("cps_simplif.bin");
    // Convert opencv mat to ncnn mat
    ncnn::Mat input = ncnn::Mat::from_pixels(img2.data, ncnn::Mat::PIXEL_BGR, img2.cols, img2.rows);
    const float mean_vals[3] = {0.485, 0.456, 0.406};
    const float norm_vals[3] = {0.229, 0.224, 0.225}; //[0.485, 0.456, 0.406]),std=np.array([0.229, 0.224, 0.225]
    input.substract_mean_normalize(mean_vals, norm_vals);
    // ncnn forward calculation
    ncnn::Extractor extractor = net.create_extractor();
    extractor.input("input.1", input);
    ncnn::Mat output0;
    extractor.extract("1035", output0);

    //ncnn::mat ->>>>> cv::mat
    cv::Mat a(input_height,input_width, CV_8UC3);
    output0.to_pixels(a.data, ncnn::Mat::PIXEL_BGR2RGB);
    
    cv::imwrite("ncnninfer.png", a);
    
    // pretty_print(output0);
    // pretty_print(output1);

    cout<<"done"<<endl;
    return 0;
}

Only segmentation fault (core dumped) is reported after running

No core file is generated. Check through ulimit -c, the size of core file is unlimited and there is no problem. This method solves the problem of not generating core file

With core file

Pass under the terminal

apt-get update
apt-get install gdb

Install GDB

Installation completed, passed

gdb ./Execution file name   core

The core here can be modified according to its own core file name.
the error is found at:

Corresponding to the reasoning code above

output0.to_pixels(a.data, ncnn::Mat::PIXEL_BGR2RGB);

It is the code to realize the conversion from ncnn:: mat to cv:mat. After debugging, it is found that the reasoning results of ncnn are all Nan, which leads to the conversion failure

Adjust the previous input, normalization is not done well.

C++ Compile Error: error: invalid conversion from ‘void*‘ to ‘char*‘ [-fpermissive]

error: invalid conversion from ‘void*‘ to ‘char*‘ [-fpermissive]

#include <stdio.h>
#include<malloc.h>
#define IN
#define OUT

// Get file size
int FileSize(IN char *file)
{
	FILE *fil;
	fil = fopen(file,"rb");
	fseek(fil,0L,SEEK_END);
	int filesize = ftell(fil);
	fseek(fil,0,0);
	return filesize;
}

// read the file
int ReadFileData(IN char *fileName, OUT char *filedata)
{
	FILE *fpIN;
	int fileSizes = FileSize(fileName);
	fpIN = fopen(fileName,"rb");
	fread(filedata,1,fileSizes,fpIN);
	fclose(fpIN);
}

// write the file
int WriteToFile(char *filedata, int size, OUT char *outFileName)
{
	FILE *fpOUT;
	fpOUT = fopen(outFileName,"w+");
	fwrite(filedata,1,size,fpOUT);
	fclose(fpOUT);
}

int main()
{
	char *origin_file = "test.cpp";
	int orgfilesize = FileSize(origin_file);  // Get file size



	char *file_data=  malloc(orgfilesize);      // Allocate file size memory
    if (file_data == NULL)
        return NULL;
	ReadFileData(origin_file, file_data);     // read the file
	char *outFile = "test.txt";
	WriteToFile(file_data,orgfilesize,outFile);  // write the file

	return 0;
}

The following line of code

char *file_data=  malloc(orgfilesize);

Malloc function is used to allocate space in C language. The return type is void*. Void* indicates a pointer of undetermined type. C. C++ specifies that the void* type can cast any other type of pointer.

The malloc() function actually finds a space of a specified size in memory and ranges the first address of that space to a pointer variable.
Here the pointer variable can be a single pointer or the first address of an array.
It depends on the size of the malloc() function.

Use GCC compilation to directly pass and print out the following results

Original String: testing.

When compiling with g++, an error and warning will appear, as follows

error: invalid conversion from ‘void*’ to ‘char*’ [-fpermissive]
warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

The reason for the error is that c++ is designed to be more secure than C, and it cannot automatically convert void * to other pointer types.

The reason for warning is that the program attempts to convert the string literal (const char [] in c++ and char [] in C language) to char * type,,

char *file_data= (char*) malloc(orgfilesize); 
# The return value of the malloc function is a void*, which is assigned to a variable by adding a forced conversion in front of malloc

Introduction to malloc function
malloc function is often used in C language and c++ to dynamically allocate memory space for variables. Malloc requests the system to allocate memory space of the specified size bytes

function void malloc(int size)

explain:

Malloc requests the system to allocate memory space of the specified size bytes. If the allocation is successful, a pointer to the allocated memory is returned; otherwise, a null pointer is returned
this function is included in the header file: \include < malloc.h> you should import the header file *< malloc.h>  or  < stdlib.h>** when you are using

Note: when the memory is no longer used, the free() function should be used to free the memory block
Common usage

1. When you do not know the definite memory required by a variable

For example, when defining an array, the size of the array is not known until the program is compiled. In this case, you can use the malloc function

int main()
{
	int n;
	scanf("%d",&n);
	int *m=(int *)malloc(sizeof(int)*n);  //Defining a pointer variable that points to n int is equivalent to opening an array of n int elements.
	// If n is very large, more than 1000000, then opening an int array of this size will cause a stack overflow.
	int m[1000000]; //Stack overflow will occur.
	return 0;
}

2. Allocate space for structural variables
define a common variable of structure type. You can dynamically apply for memory without malloc. The CPU will allocate memory for structure variables.

typedef struct
{
    int n;
    char *p;
}node;

int  main()
{
	node a;  //The definition is a structured ordinary variable, you can request memory without using malloc, the CPU will allocate memory for this structured variable
    a.n=4;
    printf("%d",a->n); //can output successfully
    node *b; //defines a structure pointer variable, the CPU will open up memory for this pointer with a size of 4 bytes. But to store the data members of the structure this space is not enough, it will raise a segment error, at this time you must malloc request a structure type size of dynamic memory to store the data members.
    //b=(node *)malloc(sizeof(node));
    printf("%d",sizeof(b)); // use sizeof(b) to see the size of b is 4
    char p[]="abcd";
    printf("%d",b->n);
    (a->p)=p;
    printf("%c",a->p[0]);
    return 0;
}

If malloc is not used to allocate space for structure pointer variable B, warning: ‘B’ is used uninitialized in this function [-wuninitialized]|.

3. When defining a structure, you need to pay attention to allocating space for its members in turn
in normal use, after allocating space for a structure with malloc function, operate on its member variable (pointer type).

For example, when the pointer p=null, it will always report “program received signal SIGSEGV, segmentation fault.”
use malloc function

[Solved] Linux C++ Compile Error: c++: internal compiler error: Killed (program cc1plus)

Compilation error:

/home/service/rpc/goya-rpc/src/rpc_server_impl.cc: In member function ‘void goya::rpc::RpcServerImpl::OnCallbackDone(google::protobuf::Message*, boost::shared_ptr<boost::asio::basic_stream_socket<boost::asio::ip::tcp> >)’:
/home/service/rpc/goya-rpc/src/rpc_server_impl.cc:101:44: warning: ‘int google::protobuf::MessageLite::ByteSize() const’ is deprecated (declared at /home/service/rpc/goya-rpc/thirdparty/install/include/google/protobuf/message_lite.h:430): Please use ByteSizeLong() instead [-Wdeprecated-declarations]
   int serialized_size = resp_msg->ByteSize();
                                            ^
c++: internal compiler error: Killed (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <http://bugzilla.redhat.com/bugzilla> for instructions.
make[2]: *** [src/CMakeFiles/goya-rpc.dir/rpc_server_impl.cc.o] Error 4
make[1]: *** [src/CMakeFiles/goya-rpc.dir/all] Error 2
make: *** [all] Error 2

The reason for the error is that the compiling machine is running out of memory, and a large number of template extensions need enough memory.

#View linux memory usage by.
1.ps aux --sort -rss
2.free -m
3.top  Press [shift + M keys] to arrange them in reverse order
4.cat /proc/meminfo

Solution:

You can solve this problem by temporarily using swap partitions:

=[step 1: operate as follows]=========================================

Sudo DD if=/dev/zero of=/swapfile bs=64m count=16
\count is the size of the increased swap space. 64M is the block size, so the space size is bs*count=1024mb
sudo mkswap /swapfile \

=[step 2: close release] ==================================================================================

Sudo swapoff /swapfile
sudo RM /swapfile
then continue to perform your relevant operations…

Note: if you still prompt “g++: internal compiler error: killed (program cc1plus)” after creating the temporary space, it may be because the allocated space is not large enough. You can continue to allocate more space.

[Solved] Ubuntu Eclipse C/C++ Error: launch failed.binary not found

Questions

Running on windows, there is either a problem with the installation of mingw64, or the header file cannot be found. Anyway, it is to verify whether the simulator can be used. What is the trouble? Just switch to Linux. The following are the results of running on Ubuntu.

Process

To run the square studio export project, follow the readme of the exported project,

    1. install gcc
sudo apt-get install gcc g++ gdb build-essential
    2. install sdl
sudo apt-get install libsdl2-dev

3. Install eclipse c/c++
4. Select the parent folder of the exported project as “Workspace”
5. Select File->Import->General->Exisiting project into Workspace click “Next” and browse the project
6. Build the project with Project->Build
7. Run the project with Run->Run.
Then report an error: could not found lpng

 

Solution:

    1Install lpng
sudo apt-get install libpng-dev

2. install CDT

help-> Check for updates

check CDT and install 

3. Modify the compiler

4. Just follow steps 6 and 7 above. The effect drawing is as follows

How to Solve OpenCV CVUI Error: LINK2019

OpenCV CVUI Error: LINK2019

1、Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol “void __cdecl cvui::init(class std::basic_string<char,struct std::char_traits,class std::allocator > const &,int,bool)” (?init@cvui@@YAXAEBV?b a s i c s t r i n g @ D U ? basic_string@DU?basic 
s
​
 tring@DU?char_traits@D@std@@V?$allocator@D@2@@std@@H_N@Z) referenced in function main

2、Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol “bool __cdecl cvui::button(class cv::Mat &,int,int,class std::basic_string<char,struct std::char_traits,class std::allocator > const &)” (?button@cvui@@YA_NAEAVMat@cv@@HHAEBV?b a s i c s t r i n g @ D U ? basic_string@DU?basic 
s
​
 tring@DU?char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function main DotMatrix

3、Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol “void __cdecl cvui::printf(class cv::Mat &,int,int,double,unsigned int,char const *,…)” (?printf@cvui@@YAXAEAVMat@cv@@HHNIPEBDZZ) referenced in function main

4、Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol “void __cdecl cvui::update(class std::basic_string<char,struct std::char_traits,class std::allocator > const &)” (?update@cvui@@YAXAEBV?b a s i c s t r i n g @ D U ? basic_string@DU?basic 
s
​
 tring@DU?char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function main DotMatrix

 

Solution:

Add the codes below before the .cpp

#define CVUI_IMPLEMENTATION
#include "cvui.h"

[Solved] CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage

CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage

1. Error report Description:

Error reporting when building C + + program with cmake:

$ cmake .
-- Building for: NMake Makefiles
CMake Deprecation Warning at CMakeLists.txt:1 (cmake_minimum_required):
  Compatibility with CMake < 2.8.12 will be removed from a future version of
  CMake.

  Update the VERSION argument <min> value or use a ...<max> suffix to tell
  CMake that the project does not need compatibility with older versions.


CMake Error at CMakeLists.txt:2 (project):
  Running

   'nmake' '-?'

  failed with:

   The system cannot find the specified file.


CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
-- Configuring incomplete, errors occurred!
See also "C:/Users/eren.luo/Desktop/test/CMakeFiles/CMakeOutput.log".

2. Solution:

P. S. mingw64/bin and cmake have been added to the environment variable.

Modify

cmake .

to:

cmake -G "MinGW Makefiles" .

Use the following commands to run:

mingw32-make.exe all

3. the version of C++ and cmake:

  1. cmake-3.23.1-windows-x86_64.msi
  2. mingw-w64-install.exe

System: Windows 10

[Solved] VScode Run C++ File Error: fatal error:opencv2\core.hpp:No such file or diretory

Run c++ file with vscode error: fatal error: opencv2\core.hpp:No such file or diretory

The main error is that the corresponding header file cannot be found in the header file directory!
C header file directory %MINGW_PATH%/include under the header file, which has strcpy and other c function declaration.
C++ header file directory %MINGW_PATH%/lib/gcc/mingw32/4.4.0/include/c++ under the header file, which has the declaration of std::string class.
//home directory
MINGW_PATH=D:/MinGW

//C header file directory
C_INCLUDE_PATH=%MINGW_PATH%/include;%MINGW_PATH%/lib/gcc/mingw32/3.4.5/include

//C++ header file directory
CPLUS_INCLUDE_PATH=%MINGW_PATH%/include/c++/3.4.5;%MINGW_PATH%/include/c++/3.4.5/mingw32;%MINGW_PATH%/include/c++/3.4.5/backward;% C_INCLUDE_PATH%

//In QTSDK with MinGW the C++ header files are in the lib folder
CPLUS_INCLUDE_PATH=%MINGW_PATH%/lib/gcc/mingw32/4.4.0/include/c++;%C_INCLUDE_PATH%

//library directory
LIBRARY_PATH=%MINGW_PATH%/lib;%MINGW_PATH%/lib/gcc/mingw32/3.4.5

//executable program directory
PATH=%MINGW_PATH%/bin;%MINGW_PATH%/libexec/gcc/mingw32/3.4.5

[Solved] A-LOAM Ceres Compile Error: error: ‘integer_sequence’ is not a member of ‘std‘

The reason may be that Ceres did not specify the C + + version, but a-loam did. So make a-loam consistent with Ceres

Add the following code to cmakelists of a-loam

# Set the C++ version (must be >= C++14) when compiling Ceres.
#
# Reflect a user-specified (via -D) CMAKE_CXX_STANDARD if present, otherwise
# default to C++14.
set(DEFAULT_CXX_STANDARD ${CMAKE_CXX_STANDARD})
if (NOT DEFAULT_CXX_STANDARD)
  set(DEFAULT_CXX_STANDARD 14)
endif()
set(CMAKE_CXX_STANDARD ${DEFAULT_CXX_STANDARD} CACHE STRING
  "C++ standard (minimum 14)" FORCE)
# Restrict CMAKE_CXX_STANDARD to the valid versions permitted and ensure that
# if one was forced via -D that it is in the valid set.
set(ALLOWED_CXX_STANDARDS 14 17 20)
set_property(CACHE CMAKE_CXX_STANDARD PROPERTY STRINGS ${ALLOWED_CXX_STANDARDS})
list(FIND ALLOWED_CXX_STANDARDS ${CMAKE_CXX_STANDARD} POSITION)
if (POSITION LESS 0)
  message(FATAL_ERROR "Invalid CMAKE_CXX_STANDARD: ${CMAKE_CXX_STANDARD}. "
    "Must be one of: ${ALLOWED_CXX_STANDARDS}")
endif()
# Specify the standard as a hard requirement, otherwise CMAKE_CXX_STANDARD is
# interpreted as a suggestion that can decay *back* to lower versions.
set(CMAKE_CXX_STANDARD_REQUIRED ON CACHE BOOL "")
mark_as_advanced(CMAKE_CXX_STANDARD_REQUIRED)

There are other methods as follows, but I didn’t try

Modifying cmake: set the C + + standard:

set(CMAKE_CXX_FLAGS "-std=c++11")

Change to

set(CMAKE_CXX_STANDARD 11)

[Solved] spdlog reports an error After updating Ubuntu 22.04

After updating Ubuntu 22, spdlog and FMT report errors, mainly due to some unclear problems in the FMT library

Solution:

1. Copy the header file under include/FMT of FMT Library

to this directory

2. In spdlog/include/spdlog/fmt/bundled/core.h add a macro definition of FMT_NOEXCEPT near line 154, which is the following code

// Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature).
#ifndef FMT_USE_NOEXCEPT
#  define FMT_USE_NOEXCEPT 0
#endif

#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
    FMT_GCC_VERSION >= 408 || FMT_MSC_VER >= 1900
#  define FMT_DETECTED_NOEXCEPT noexcept
#  define FMT_HAS_CXX11_NOEXCEPT 1
#else
#  define FMT_DETECTED_NOEXCEPT throw()
#  define FMT_HAS_CXX11_NOEXCEPT 0
#endif

#ifndef FMT_NOEXCEPT
#  if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT
#    define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT
#  else
#    define FMT_NOEXCEPT
#  endif
#endif

3. Recompile and install spdlog Library

cmake -S spdlog -B /tmp/build/
cd /tmp/build && make
sudo make install

[Solved] error converting to execution character set illegal byte sequence

Today, after writing a program, I found that the compiler always reports an error: error converting to execution character set illegal byte sequence. When compiling by default, it is parsed according to UTF-8, and when the character set is not specified, it is always treated as UTF-8. So you have to add the following in settings->compiler->Global compiler settings->Other options:

-fexec-charset=GBK
-finput-charset=UTF-8

The former represents the encoding interpretation format of the input file during compilation, and the latter represents the encoding format used for the display of the generated execution file during execution.

At the same time. In settings -> Editor-> gernal settings-> Other settings, set the file encoding format saved by default to UTF-8, and keep the encoding formats of both sides the same.

But after I did this, I found it useless… Later, I found that my program didn’t know when it was changed to ANSI format, so it had been either compiled incorrectly or Chinese garbled.

To solve this problem, you can open the code file with notepad and select the file – & gt; How to select the encoding format of UTF-8 to save as.