Tag Archives: c++

Solve the error reported by vscode referring to C + + external library

visual studio code has been used for some time, and I am deeply impressed by its compactness and beauty.

Recently, I did two computer graphics experiments, one of which must reference an external graphics library, but I kept reporting errors when using vscode to complete such a “simple” work 😢😢。 It even made me give up using it for a time. (of course, the heavyweight vs2017 soon persuaded me back! 😂)

Today, I finally decided to find out and solve this problem. 🤜🤜

Here are some gains (including principles and solutions)

The difference between G + + and GCC

Conclusion: writing C + + and choosing G + + is better!

Tasks.json and c_cpp_properties.json

The includepath in the c_cpp_properties.json file will become the key to the internal IntelliSense of the editor, but it has nothing to do with the compilation process. (tip: Ctrl + Shift + P Enter Edit configurations (UI) to automatically configure the relevant parameters of the generated c_cpp_properties.json file by selecting options in the graphical interface)

The parameters contained in args in tasks. JSON file will be used as command line parameters at compile time (i.e. Ctrl + F5).

- I dependency path you can specify the dependency path of the external library to achieve the effect of importing external packages.

Conclusion: to import an external library, you need to configure includepath in the c_cpp_properties.json file and args in the tasks. JSON file at the same time, so that no error is reported in both the development process and the compilation process.

Compiling and running process of C + + program

Compile the CPP source file through G + + file name 1.cpp - O file name 2. Exe , and specify the compiled exe program name through the - O parameter.

Directly enter the EXE file name (including suffix) to run the EXE executable.

Solution – discard plug-ins or as internal Libraries

It is possible that you have installed the C/C + + compile run plug-in, which can quickly compile and run programs by typing F6 on windows. In fact, it helps you realize the two steps of the above compilation process. However, the flexibility of command-line parameters is naturally abandoned…

So abandon the plug-in decisively.  ̄ □  ̄ | after abandoning the plug-in and configuring the parameters of the two files, directly type Ctrl + F5 to complete the compilation and operation correctly.

When compiling the default library, you do not need to take the - I parameter. In other words, the location of the internal library does not need to be specified. At this time, you can manually migrate the location of the external library to the location of the default library to reference the external library. At this time, you can completely do not configure the parameters of the two files.

How to deal with the prompt “dereferencing type punned pointer will break strict aliasing rules” when compiling C?

It’s about 35814; it’s about static writing and final writing! >>

1. For example:

char my_array[10];

*(int *)my_array = 0xaabbccdd;

2. Amendment is the most serious problem:

char my_array[10];

int tmp =0xaabbccdd;

memcpy(my_array, & tmp, sizeof(tmp));

Error lnk2026: module unsafe for safeseh image

Geeks, please accept the hero post of 2021 Microsoft x Intel hacking contest>>>

When compiling old projects, I found that there are two ways on the Internet, both of which can be used. In essence, they are the same two ways. Here are listed for your convenience

Method 1( http://www.cnblogs.com/loongfee/archive/2012/10/25/2738322.html )

Just change it to No. This is more convenient

Method 2

Or select command line for this interface

1. Click the command line property page

2. Type/safeseh: no into the “additional options” box, and then click apply

From: http://blog.csdn.net/wujunokay/article/details/47168589

It’s hard to say what’s on the Internet. The one on the website above said he was original, but the first one in front of him was published nearly three years ago

The following one is even more extraordinary. In 2009, he wrote a plan for this problem( http://blog.csdn.net/lijiawlm/article/details/4406837 )

Original text:

You may encounter this problem when compiling the driver, especially when writing the C + + driver

At this point, you need to add a sentence to the source file

NO_ SAFESEH = 1

This will disable the safeseh compilation option

C++ error: cannot bind non-const lvalue reference of type ‘myString&’ to an rvalue of type ‘m…

Look at the code first (if you don’t want to look at the code, you can directly look at the problem description after the code)

//header.h
#ifndef _HEADER_H
#define _HEADER_H
#define defaultSize 128
#include<iostream>
#include<string.h>
using namespace std;
class myString
{
	private:
		char *ch;
		int curLength;
		int maxSize;
	public:
		myString(int sz=defaultSize);
		myString(const char *init);
		myString(const myString& ob);
		~myString(){delete []ch;}
		void print();
		int Length()const;
		myString operator()(int pos, int len);
		myString& operator = (myString& ob);
};
myString& myString::operator = (myString& ob)
{
	if(&ob!=this)
	{
		delete[]ch;

		this->ch = new char[ob.maxSize];
		this->maxSize = ob.curLength;
		strcpy(this->ch, ob.ch);
		this->curLength = ob.curLength;
	}
	else
	{
		cerr<<"String copy error\n";
	}
	return *this;
}

myString myString::operator()(int pos, int len)
{
	myString temp;
	if(pos<0 || len<=0 || pos+len-1>=this->maxSize)
	{
		temp.curLength = 0;
		temp.ch[0] = '\0';
	}
	else
	{
		if(pos+len-1 >= this->curLength)
			len = this->curLength-pos;
		temp.curLength = len;
		for(int i=0,j=pos; i<len; ++i,++j)
			temp.ch[i] = this->ch[j];
		temp.ch[len] = '\0';
	}
	return temp;
}

int myString::Length()const
{
	return this->curLength;
}

void myString::print()
{
	cout<<this->ch<<endl;
}

myString::myString(int sz)
{
	this->maxSize = sz;
	this->ch = new char[this->maxSize+1];
	if(this->ch == NULL)
	{
		cerr<<"Allocation ERROR\n";
		exit(1);
	}
	this->curLength = 0;
	ch[0] = '\0';
}

myString::myString(const char *init)
{
	int len = strlen(init);
	this->maxSize = (len > defaultSize) ?len : defaultSize;
	this->ch = new char[this->maxSize+1];
	if(this->ch == NULL)
	{
		cerr<<"Application Memory ERROR\n";
		exit(1);
	}

	this->curLength = len;
	strcpy(this->ch, init);

}

myString::myString(const myString& ob)
{
	this->maxSize = ob.maxSize;
	this->ch = new char[this->maxSize+1];
	if(this->ch == NULL)
	{
		cerr<<"Application Memory ERROR\n";
		exit(1);
	}
	this->curLength = ob.curLength;
	strcpy(this->ch, ob.ch);

}

#endif
//main.cpp
#include"header.h"

int main()
{
	myString st(10), st1("ABCDEFG");
	myString st2(st1);
	st.print(), st1.print(), st2.print();
	st = st1(0, 4);//???
	st.print();
	return 0;
}

This is a string class. The problem is two symbol overloads, () and=

() overloading is to slice a string object and return a temporary object. Needless to say, = overloading is assignment

The problem is that it is always impossible to assign the sliced temporary object to the object before the equal sign

After searching on the Internet, I found a similar problem

https://blog.csdn.net/u011068702/article/details/64443949

That is to say, there is a temporary variable in ST1 (0,4). When the temporary variable is passed to st, because in the = overloaded function declaration, the parameter is mystring & amp;, It’s not a constant reference

This error is a semantic limitation of the C + + compiler

If a parameter is passed in as a non const reference, the C + + compiler has reason to think that the programmer will modify the value in the function, and the modified reference will play a role after the function returns. But if you pass in a temporary variable as a non const reference parameter, because of the particularity of the temporary variable, the programmer cannot operate the temporary variable, and the temporary variable may be released at any time. Therefore, generally speaking, it is meaningless to modify a temporary variable, The C + + compiler adds the semantic restriction that temporary variables cannot be used as non const references

After understanding this semantics, it’s easy to add const constant restrictor to = overload parameter

(class = overloaded function declaration, don’t forget to add const)

Add the running result of later program

Yes, that’s right

Conclusion:

Temporary variables in C + + cannot be used as reference parameters of non const

Updated on December 14, 2019

Recently, I saw a similar problem, that is, C + + 11

int i=0;
++++i;//right
i++++;//wrong

We know that the former + + is to automatically add the object and then return the object, and the latter + + will first return the current value of the record, then automatically add, and finally return an unnamed temporary object. Then I + + + is to automatically add the unnamed temporary object returned by the first latter + +, which is meaningless to C + +, so it cannot be compiled// PS. this is often said to take one corner with three corners

[C + +] there is an error in compiling C program under Linux’s Ubuntu: the solution of “strain ‘\ \ 302’ or ‘\ \ 240’ in program”

[C + +] there is an error in compiling C program under Linux’s Ubuntu: the solution of “strain ‘\ \ 302’ or ‘\ \ 240’ in program”

Reference article:

(1) [C + +] there is an error in compiling C program under Linux’s Ubuntu: the solution of “strain ‘\ \ 302’ or ‘\ \ 240’ in program”

(2) https://www.cnblogs.com/johnnyzen/p/7995666.html

Let’s make a note.

Go to: install C extended compiler environment of Python under windows (solve the problem of “unable to find vcfarsall. Bat”

Individual articles are original or translated unless reprinted

Individual articles are welcome to be reprinted in various forms, but those over 18 years old are requested to indicate the source of the article, respect my labor and your intelligence

Link to this article: http://www.cnblogs.com/fbwfbi/p/4509622.html

N hasn’t started blogging for a long time. I always feel that I need to remember something casually. I’ve lost some things, technologies and tools. I’d better record every bit of them

In windows, PIP is used to install some third-party libraries of Python. Many of them use C to write some extensions and need to use VC + + compiler to compile and install (or use MinGW, generally not recommended). Otherwise, it will appear “ unable to find vcfarsall. Bat “. For example, python 2.7 needs to use VS2008 C + + compiler, while python3 to python3.4 (python3.5 will use vs2015) will use VS2010 to compile. However, anyone who has ever installed vs, a huge and bloated IDE, knows that it comes with a lot of Microsoft plug-ins that you don’t know whether they are useful or not. They occupy a lot of space on C disk and start slowly, although the interface function of IDE is barely passable. If the computer configuration is general, this thing will make n cards, generally do not do related development, there is no need to install the entire vs. For Python 2.7, Microsoft has a conscience. It directly launched Microsoft Visual C + + compiler for Python 2.7, which can be downloaded and installed directly. Then, in the start menu – “all programs”, find the corresponding directory, and according to your platform and python Version (select x86 or x64), click the corresponding command prompt to run. In this CMD window, you can enter the set command to check the environment variables. It is found that the parameters include =, path =, lib =, and libpath = have been set, so you can enter them directly

pip install numpy

You can install and compile the corresponding third-party modules and libraries. Sometimes the compilation process is long and you need to wait patiently

But for Python 3, it’s not so convenient. Because my Python 3.4 is 64 bit, it’s obviously impossible to use VS2010 express directly, because it only has x86 version by default, not 64 bit. Refer to a question and answer in stack overflow

Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

According to the above suggestions, I get the corresponding solution on this machine. First install VS2010 express, then install windows SDK 7.1, and finally install a 64 bit compiler patch

  Microsoft SDK 7.1 (Windows 7)

  VC-Compiler-KB2519277

PS: before installing SDK 7.1, please uninstall VC redistribute 2010 related component packages (including x86 and x64), otherwise an error will be reported

After completing the above steps, the basic MSVC compilation environment (including x64) has been configured. However, if you compile a project in the future, such as building a Qt5 project, the following errors will appear:

c:\program files (x86)\microsoft visual studio 10.0\vc\include\intrin.h(26):fatal error C1083: Cannot open include file: ‘ammintrin.h’: No such file or directory

At this time, you can download the corresponding ammintrin. H from the Internet, and put it in the directory of C:// program files (x86) \ \ Microsoft Visual Studio 10.0 \ \ VC \ \ include \, which can be downloaded from the following Baidu Library:

ammintrin. H header file, which is required after installing kb2519277 patch in Windows SDK 7.1

After installation, in the start menu, find “windows SDK 7.1 command prompt”, click Run, and set the corresponding compilation environment through setenv in the shell, as shown in the following figure:

After setting “setenv/x64”, you can install the corresponding package in the 64 bit compiling environment

At this point, you may need to mention that after setting up the environment, you can install numpy in Python 2.7 and python 3.4 respectively. You find that py2 is OK, but PY3 fails to install and compile link (you have tested it in the virtual machine before, but PY3 installation is OK). Why?Please compare the following two pictures:

Obviously, when py2 is installed, libpath under the link command line uses “” to cause it. Therefore, the path with spaces will not partition the parameters. PY3 is not so detailed. I don’t know whether it is the fault of PIP and setuptools calling the CMD command or the bug in distutils. Anyway, the installation path of PY3 can’t have spaces. So I adjusted the installation path of python3, that is, there is no space, and the compilation is successful

Of course, this is just a VC + + compilation environment. For a numerical calculation library like SciPy, you need a FORTRAN compiler to install it. Obviously, the compilation and installation under windows is far less convenient than that under Linux (except that the package name is not easy to remember and the package dependence is troublesome). GCC and gfortran are ready-made, and apt get is also ready-made. Therefore, if you develop and test under windows, you can directly use a large number of compiled and packaged windows wheel installation packages provided by the University of California, Irvine (UCI), which contain numpy, SciPy, Matplotlib and other module libraries for numerical analysis and scientific calculation, and all of them are MKL versions. Download the corresponding version and directly use “PIP install XXX. WHL” to complete the installation. The WHL file is just like a zip file. You can also use the compression software to unpack it and put it in the corresponding lib/site packages directory. Of course, you can also use the python customized environment version Anaconda , which has directly integrated the above packages, including the easy-to-use repl tool like IPython and CONDA package management

How to Solve MSB8020 The build tools for v141 (Platform Toolset = ‘v141‘) cannot be found. To build using the

Problem solving

MSB8020 The build tools for v141 (Platform Toolset = ‘v141’) cannot be found. To build using the v141 build tools, please install v141 build tools. Alternatively, you may upgrade to the current Visual Studio tools by selecting the Project menu or right-click the solution, and then selecting “Retarget solution”. ChineseSimplified C:\Program Files (x86)\MSBuild\ Microsoft.Cpp \v4.0\V140\ Microsoft.Cpp.Platform .targets 57

Solutions

Msb8020 could not find the build tool for v141 (platform toolset =’v141 ‘). To build using the v141 build tool, install the v141 build tool. Alternatively, you can upgrade to the current version of visual studio tools, Microsoft. CPP, v4.0, V140, by selecting the Project menu or right-click solutions and then selecting retargeting solutions\ Microsoft.Cpp . platform objective 57

Solutions

When this problem occurs, you can see that the project you want to build is from vs2017, and its C + + toolset is v141. Of course, we can also choose to install toolset v141 in vs2019. In vs2019, go to tools = &> get tools and functions = &> install the C + + build tools of vs2017.
Note: the vs 2015 platform toolset is V140, the vs 2017 platform toolset is v1141, and the vs 2019 platform toolset is v142.

No build tools were found for & lt; platform &> (platform toolset = “& lt; version &>”. To build using the & lt; version &> build tool, install the & lt; platform &> build tool. Alternatively, you can upgrade to the current visual studio tools by selecting the Project menu or right-click the solution, and then select retarget solution.

[leetcode] 280. Wiggle sort

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] &>= nums[2] <= nums[3]….

For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].

To give an array without sorting, reorder it to nums [0] & lt; = nums [1] &> = nums [2] & lt; = nums [3].

Solution: traverse the array, if it is an odd position and its value is larger than the next, then exchange its value, if it is an even position and its value is smaller than the next, then exchange its value. The time complexity is O (n). Note that the difference between the index and the actual position is 1, so the parity is opposite.

Java:

public class Solution {
    public void wiggleSort(int[] nums) {
        if (nums == null || nums.length < 2) return;
        for (int i = 1; i < nums.length; i++) {
            if ((i % 2 == 0 && nums[i] &> nums[i - 1]) || (i % 2 == 1 && nums[i] < nums[i - 1])) {
                int tmp = nums[i];
                nums[i] = nums[i - 1];
                nums[i - 1] = tmp;
            } 
        }
    }
}  

Java:

public class Solution {
    public void wiggleSort(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        for (int i = 1; i < nums.length; i++) {
            if (i % 2 == 1) {
                if (nums[i] < nums[i - 1]) {
                    swap(nums, i);
                } 
            } else {
                if (nums[i] &> nums[i - 1]) {
                    swap(nums, i);
                }
            }
        }
    }
    
    private void swap(int[] nums, int i) {
        int tmp = nums[i - 1];
        nums[i - 1] = nums[i];
        nums[i] = tmp;
    }
}  

Python:

# Time:  O(n)
# Space: O(1)
class Solution(object):
    def wiggleSort(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        for i in xrange(1, len(nums)):
            if ((i % 2) and nums[i - 1] &> nums[i]) or \
                (not (i % 2) and nums[i - 1] < nums[i]):
                # Swap unordered elements.
                nums[i - 1], nums[i] = nums[i], nums[i - 1]

C++:

// Time:  O(n)
// Space: O(1)
class Solution {
public:
    void wiggleSort(vector<int&>& nums) {
        for (int i = 1; i < nums.size(); ++i) {
            if (((i % 2) && nums[i] < nums[i - 1]) ||
                (!(i % 2) && nums[i] &> nums[i - 1])) {
                // Swap unordered elements.
                swap(nums[i], nums[i - 1]);
            }
        }
    }
}; 

C++:

// Time Complexity O(nlgn)
class Solution {
public:
    void wiggleSort(vector<int&> &nums) {
        sort(nums.begin(), nums.end());
        if (nums.size() <= 2) return;
        for (int i = 2; i < nums.size(); i += 2) {
            swap(nums[i], nums[i - 1]);
        }
    }
};

C++:

// Time Complexity O(n)
class Solution {
public:
    void wiggleSort(vector<int&> &nums) {
        if (nums.size() <= 1) return;
        for (int i = 1; i < nums.size(); ++i) {
            if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] &> nums[i - 1])) {
                swap(nums[i], nums[i - 1]);
            }
        }
    }
};

>>

Similar theme:

[LeetCode] Wiggle Sort II free action II

All LeetCode Questions List Total

The solution of “the windows SDK version for 8.1 was not found” in vs2017 C + + compilation

Recently, win7 64 bit ultimate + Visual Studio 2017 was installed. It was found that there was an error in the SDK when compiling the program. The solutions on the Internet were similar, but they were not very good. After a lot of twists and turns, it was finally a perfect solution.

At compile time, vs2017 reported the following error:

vs2017 error MSB8036: The Windows SDK version 8.1 was not found.

Causes and solutions:

The main reason for this SDK version selection problem is that vs2017 uses Windows SDK 8.1 by default, but actually vs2017 does not contain this file. When compiling, vs cannot find this file, so it will report an error.

At this time, you only need to download the latest version of the SDK to install. Because of the downward compatibility of the SDK, this problem can be solved in win7/win8/win10.

1. First of all, right-click the project to be compiled &> &> properties &> &> configuration properties &> &> general to check the version number of the windows SDK. It is found that it is 8.1, and there is no other version number option in the drop-down menu. Here, because it has been installed, a new version number appears.

After confirmation, I found some online methods. For example, right-click on the project and select “retarget SDK version” to pop up the new version installation option. I don’t have this one. I can only download and install it myself.

2. Log in to the official website of windows SDK: https://developer.microsoft.com/zh-cn/windows/downloads/windows-10-sdk , download the windows 10 SDK (10.0.16299.15). I can download the. EXE file and double-click it directly. Then other options can be installed on Disk C by default. The installation time may be long or short. I spent 2 hours to install last night, but it only took 10 minutes this morning.

(someone on the Internet said that it must be installed in the SDK folder under the installation path of vs. there is no need to test it by yourself. It can be installed by default, and it does not affect the use.)

Pay attention to check the version compatibility of the SDK. The above downloaded version is the latest and fully applicable to win7 system. The details can be described in the above website, as shown in the figure:

3. After the installation, re execute the viewing method in step 1, and you can find that the new version number 10.0.16299.15 appears in the drop-down menu. Select the version number and click the application and confirmation below to compile the program again. It is found that the program can pass successfully.

Problem solving.