Tag Archives: C language

Microsoft Visual C++ 14.0 or greater is required. Get it with “Microsoft C++ Build Tools“

Alipay’s online payment function has recently been developed to download and pay the SDK package. The wrong presentation is as follows:
reported false prompts: Microsoft Visual C++ 14 or greater is required. Get it it ” https://visualstudio.microsoft.com/visual-cpp-build-tools/

Reason: python3 is compiled with VC + + 14, python27 is compiled with C + + 9, and the package to install python3 needs to be compiled with C + + 14 or above

Don’t panic for small scenes

That’s the thing above. Double click the installation. Do you think it’s over?

In case of no accident, most of the installation packages you download will finally prompt you: the installation package is missing or damaged
some netizens say that it can succeed with a ladder, and others say that it can’t succeed
I uploaded an offline version here. You can try

Solved: could not find the task ‘G + + build active file, leetcode algorithm ACM compilation and debugging

Project scenario:

Environment: Ubuntu 20.04

Tool: vscode

Because leetcode can’t debug the code (for members), it’s necessary to configure the local environment to run the code.

Leetcode’s code is to help you configure all the environments. You only need to write the core code, but you need to write all the code yourself during the interview. It’s ACM mode (Baidu ACM). At this time, if you don’t often write all the code, it’s easy to be confused (this is what happened when I was deeply convinced in the online interview)

So it’s necessary to configure the local environment and write the whole process of algorithm implementation, including the compilation process and principle of cpp file, and the debug process can make you more familiar with the code running process.

Reference for compiling environment configuration: https://code.visualstudio.com/docs/cpp/config-linux

No Baidu, no Baidu! Look at the official statement is always the best!!! If you don’t understand English, you can right-click to translate the web page directly.

My task.json configuration: it is automatically generated. The configuration of the computer and the environment is different, so this file may be different.

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: g++ Generate activity files",
			"command": "/usr/bin/g++",
			"args": ["-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}"],
			"options": {
				"cwd": "${fileDirname}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": {
				"kind": "build",
				"isDefault": true
			},
			"detail": "Compilers: /usr/bin/g++"
		}
	]
}

My launch.json:

{
    "version": "0.2.0",
    "configurations": [
      {
        "name": "g++ build and debug active file",
        "type": "cppdbg",
        "request": "launch",
        "program": "${fileDirname}/${fileBasenameNoExtension}",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "environment": [],
        "externalConsole": false,
        "MIMode": "gdb",
        "setupCommands": [
          {
            "description": "Enable pretty-printing for gdb",
            "text": "-enable-pretty-printing",
            "ignoreFailures": true
          }
        ],
        "preLaunchTask": "g++ build active file",
        "miDebuggerPath": "/usr/bin/gdb"
      }
    ]
  }

Problem Description.
I encountered the following situation when configuring task.json for compiling C++ and debugging configuration file launch.json.


Cause Analysis.
Code encountered problems suggest direct google …
Reference: https://stackoverflow.com/questions/59106732/visual-studio-code-debugger-error-could-not-find-the-task-gcc-build-active-f

In your task.json file, no task is labeled as ‘gcc build active file’ which is required as a preLaunchTask in launch.json file.

So you can either change the label of task or change the content of preLaunchTask to make them match.

The answer is clear: task.json file this configuration

"label": "C/C++: g++ Generate activity files",

This configuration must be the same as launch. JSON

"preLaunchTask": "g++ build active file",

Solution:

Configure task.json as follows:

"label": "C/C++: g++ Generate activity files",

To be amended as follows:

"label": "g++ build active file",

—————————The following can be ignored———————————-

As long as the two values are the same. You can be like this: (yes, that’s what I changed it to.)

"label": "g++ build active file  hahaha",

[solution] warning: this statement may fall through [- wimplicit fallthrough]) encountered during GCC compilation

When practicing the switch statement in Ubuntu, if break is not added in the case statement, the warning message will pop up, causing the program to fail to compile,

root@root:~/code$ g++ -Wall -W test_switch.c -o test_switch 
test_switch.c: In function ‘int main()’:
test_switch.c:13:10: warning: this statement may fall through [-Wimplicit-fallthrough=]
   13 |    printf("1\n");
      |    ~~~~~~^~~~~~~~~~~~~
test_switch.c:15:3: note: here
   15 |   case 3:
      |   ^~~~
test_switch.c:16:10: warning: this statement may fall through [-Wimplicit-fallthrough=]
   16 |    printf("3\n");
      |    ~~~~~~^~~~~~~~~~~~~
test_switch.c:18:3: note: here
   18 |   case 5:
      |   ^~~~

At this time, adding – W when compiling the code can shield the alarm, and the code can be compiled normally

root@root:~/code$ g++ -Wall -W test_switch.c -o test_switch -w

Vs error unresolved external symbol_ Main, the symbol in the function “int”__ cdecl invoke_ main

Cause analysis

There are many reasons for this problem. The first and most common one is that there are multiple CPP files in your project, which contain multiple main functions
the second is that your code is copied from QQ or other ways (such as Notepad). In this case, the newline character may change. According to the explanation of the online boss, the newline character has many codes. If the format is wrong, there will be problems. At this time, you will be prompted to convert the source file to DOS or UNIX format, If there is a warning, it means that you are in this situation. You need to find the advanced save option in the file menu of vs (the advanced version needs to be called out in the settings, but not Baidu search), and then select window (CR LF), which means that the new line character supported by the window system indicates that the problem is solved ~
the third is that your project is created incorrectly, If your compiler’s preprocessor is not right, you can copy the code directly to the new correct project, or open the project settings and modify your preprocessor. You can search for it.

Clion new method shows undefined reference to solution

Clion new method shows undefined reference to solution

Problem solving

problem

"D:\cSoftware\CLion 2019.1.4\bin\cmake\win\bin\cmake.exe" --build D:\site\c\sm2\cmake-build-debug --target sm2 -- -j 4
-- Configuring done
-- Generating done
-- Build files have been written to: D:/site/c/sm2/cmake-build-debug
Scanning dependencies of target sm2
[ 50%] Linking C executable sm2.exe
d:/csoftware/mingw/mingw/bin/../lib/gcc/x86_64-w64-mingw32/9.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: CMakeFiles\sm2.dir/objects.a(main.c.obj): in function `main':
D:/site/c/sm2/main.c:6: undefined reference to `add'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\sm2.dir\build.make:85: sm2.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:72: CMakeFiles/sm2.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:84: CMakeFiles/sm2.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:130: sm2] Error 2

File addfunction. H

#include <stdio.h>
int add(int a,int b);

File addfunction. C

#include <stdio.h>
#include "addfunction.h"

int add(int a,int b){
    return a+b;
}

main.c

#include <stdio.h>
#include "addfunction.h"

int main() {
    int a = 1,b =2;
    int c = add(a,b);   //Here is a call to the add function in function.c
    printf("c=%d",c);
    return 0;
}

terms of settlement

Modify cmakelists.txt
and add_ Library and target_ link_ libraries

cmake_minimum_required(VERSION 3.14)
project(sm2 C)

set(CMAKE_C_STANDARD 99)

add_library(sm2lib addfunction.h addfunction.c)
add_executable(sm2 main.c)
target_link_libraries(sm2 sm2lib)

Compile .h file with error “error: backslash-newline at end of file [-Werror]:

Solution: add a blank line at the end of the file

For example, when compiling the following. H file, an error is reported

#define func1(name, begin)          \
    static thread_local A __x_y_z_agg_##name(#name); \
    (__x_y_z_agg_##name).B(begin)
    
#define func2 A::C

It needs to be changed to

#define func1(name, begin)          \
    static thread_local A __x_y_z_agg_##name(#name); \
    (__x_y_z_agg_##name).B(begin)
    
#define func2 A::C

Vs (Visual Studio) encountered a solution that could not open iostream

Recently, when configuring some projects, I couldn’t even open the iostream header file

Finally, we try to reset vs C + +, and successfully solve the problem.

My version is vs2013 in the following way

Tools -> Import and Export -> Reset all -> ..

Tools → import and export settings → reset all settings → next →

Select “save the current settings (I chose to reset directly)”,

Next → select “development language to reset (for example, Visual C + + development settings)” → finish

My CSDN first blog actually wrote this..

How to use C + + function pointer array

2015-11-24

1、 Origin

Under what circumstances did you come up with an array of function pointers?Because there are a series of sequential functions in a program recently written, and the forms of these functions are basically the same, it is necessary to judge the execution result of each step, whether the execution is successful or not. If the execution is successful, the next function will continue to be executed. If the execution fails, the terminal will execute and exit.

Because there are many functions to be executed in turn, there are five. To write code according to the conventional way of thinking is to judge the result of each step by if-else, and decide the content of the next step according to the result. At present, there are only five functions to be executed. If there are more similar functions to be executed in sequence, this function will be very long, not easy to read, and the code will not be beautiful.

Considering that the parameter list and return value of the current function are basically the same, we consider whether we can traverse the function pointer array, store the function pointer in the array and traverse the array, so as to execute the function pointed to by the corresponding pointer in turn, judge the results one by one, and do the corresponding processing. In this way, the result processing part can adopt a unified way, which is very convenient to judge, the code is also very simple and clear, and it is easy to read.

So online query related information, to understand the use of function pointer array. Through data query, the use of C + + function pointer array can be divided into two categories, one is the use of global function pointer array (the same as C language), the other is the use of C + + member function pointer array. Now the two cases are sorted out respectively.

2、 The use of global function pointer array in C

(1) Requirements

1. The parameter list and return value type of a series of functions to be called should be identical;

2. It is required to put the function pointer to be called into the function pointer array (if the function must have sequential execution, then the storage order of the function pointer should be consistent with the calling order);

3. When calling, take out the function pointer to be executed from the array and execute the corresponding function.

(2) Code case

Reference from: http://blog.csdn.net/feitianxuxue/article/details/7300291

 

#include <iostream> 

using namespace std; 

 

void function0(int); 

void function1(int); 

void function2(int); 

 

int _ tmain(int argc, _ TCHAR* argv[]) 

Void (* f [3]) (int) = {function0, function1, function2};// save the three function pointers in the array F

      intchoice;

      cout<< “Enter a number between 0 and 2,3 to end: “;

      cin>> choice;

//handle user selection

      while((choice >= 0) && (choice <3))

      {

//call a function in the array f

(* f [choice]) (choice);// F [choice] select the pointer whose position is choice in the array.

//the pointer is dereferenced to call the function, and choice is passed as an argument to the function.

             cout<< “Enter a number between 0 and 2,3 to end: “;

             cin>> choice;

      }

      cout<< “Program execution completed.” << endl;

      system(“pause”);

      return0;

}

 

void function0(int a)

{

      cout<< “You entered” << a << ” so function0 wascalled\n\n”; 

}

 

void function1(int b)

{

      cout<< “You entered” << b << ” so function1 wascalled\n\n”;

}

 

void function2(int c)

{

      cout<< “You entered” << c << ” so function2 wascalled\n\n”;

}

3、 The use of pointer array of member function in C + + class

(1) Requirements

When using the pointer array of member function in C + + class, it is different from that of C. The requirements are as follows:

1. It is required that the parameter list and return value type of the member function put into the function pointer array are completely consistent;

2. Define a function pointer array, and specify the length of the array (equal to the number of member functions to be stored), and assign the member function pointer to the corresponding array variable during initialization (if the function must have sequential execution, the storage order of the function pointer should be consistent with the calling order);

3. When calling, take out the function pointer to be executed from the array and execute the corresponding function. When calling, use “& gt; *” or “. *” to point to array elements, otherwise an error will be reported during compilation.

(2) Code case

Reference from: http://www.cppblog.com/dragon/archive/2010/12/02/135250.html

 

/*

* small program for testing pointer array of member function

* key points of the code have been marked in red

 */

#include <iostream>

using namespace std;

 

class Test

{

public:

   Test();

   ~Test();

 

private:

   void add5(){ res+=5;}

   void add6(){ res+=6;}

//this 2 is very important. If it is not written in VC, an error will be reported, but it is not reported in QT, but an error will be reported during the deconstruction!

    void (Test::*add[2])();

public:

   void DoAddAction();

   void Display();

private:

   int res;

};

 

Test::Test()

{

//pay attention to the writing here

    add[0]=&Test::add5;

    add[1]=&Test::add6;

   res=0;

}

 

Test::~Test()

{

 

}

 

void Test::DoAddAction()

{

    for (int i=0;i<2;i++)

    {

//using class member function pointer must have a call of “& gt; *” or “. *”

        (this->*add[i])();

    }

}

 

void Test::Display()

{

   cout<<“The res is:”<<res<<endl;

}

 

int main()

{

   Test * test=new Test();

   test->DoAddAction();

   test->Display();

   delete test;

   return 0;

}

4、 Summary

The above methods illustrate the method of using function pointer array in C and C + + classes. It is obvious that using function pointer array can call functions more conveniently, make the code concise and beautiful, and provide a level of code quality.

In the future program development process, we encounter similar problems. When we can use the function pointer array, we can try to only use the function pointer array to make the development easier and more fun.

Bitmap optimization and memory optimization

Is it necessary for bitmap to call recycle method in Android system

Before Android 3.0, bitmap image data was processed in the underlying C, so before Android 3.0, recycle() should be called. Although finalize() will call recycle(), students who are experienced in Java should know that there are many problems in releasing resources only by finalize()

After Android 3.0, the image data is put in a member variable mbuffer [] of the bitmap object. Therefore, it is not necessary to call recycle (). After the bitmap is set to null, the image data will be recycled by GC.

Now that Android is in the age of 5.0, it is recommended not to consider supporting versions before 3.0.

actually Bitmap.recycle This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap. When no reference points to a bitmap, GC will automatically free memory.)

Managing bitmap memory Google’s official explanation of bitmap

In addition to the steps described in Caching Bitmaps, there are specific things you can do to facilitate garbage collection and bitmap reuse. The recommended strategy depends on which version(s) of Android you are targeting. The BitmapFun sample app included with this class shows you how to design your app to work efficiently across different versions of Android.

To set the stage for this lesson, here is how Android’s management of bitmap memory has evolved:

On Android Android 2.2 (API level 8) and lower, when garbage collection occurs, your app’s threads get stopped. This causes a lag that can degrade performance. Android 2.3 adds concurrent garbage collection, which means that the memory is reclaimed soon after a bitmap is no longer referenced.

On Android 2.3.3 (API level 10) and lower, the backing pixel data for a bitmap is stored in native memory. It is separate from the bitmap itself, which is stored in the Dalvik heap. The pixel data in native memory is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash. As of Android 3.0 (API level 11), the pixel data is stored on the Dalvik heap along with the associated bitmap.

The following sections describe how to optimize bitmap memory management for different Android versions.

Memory optimization

Memory optimization from: http://my.oschina.net/u/1753339/blog/223379

It’s easy to load a picture on the UI of your application, but when you need to load a lot of pictures on the UI, the situation becomes more complicated. In many cases (such as using listview, GridView or viewpager), the images displayed on the screen can be increased continuously by sliding the screen and other events, which eventually leads to oom.

In order to ensure that the use of memory is always maintained in a reasonable range, the removed screen images are usually recycled. At this time, the garbage collector will also think that you no longer hold the reference of these images, so it will GC these images. It’s very good to use this idea to solve the problem, but in order to make the program run quickly and load pictures on the interface quickly, you have to consider the situation that the user slides some pictures back into the screen after they are recycled. At this time, reloading the image just loaded is undoubtedly the bottleneck of performance. You need to find a way to avoid this situation.

At this time, the use of memory caching technology can solve this problem, it can let components quickly reload and process images. Now let’s take a look at how to use memory caching technology to cache images, so that your application can improve the response speed and fluency when loading many images.

Memory caching technology provides a fast way to access images that occupy a lot of valuable memory of applications. The core class is lrucache (this class is provided in the package of android-support-v4). This class is very suitable for caching images. Its main algorithm principle is to store the most recently used objects in LinkedHashMap with strong references, and remove the least recently used objects from memory before the cache value reaches the preset value.

In the past, we often used a very popular implementation of memory caching technology, namely soft reference or weak reference. However, this method is no longer recommended, because since Android 2.3 (API level 9), the garbage collector tends to recycle objects with soft references or weak references, which makes soft references and weak references unreliable. In addition, in Android 3.0 (API level 11), the image data will be stored in the local memory, so it can not be released in a predictable way, which has the potential risk of causing the memory overflow and crash of the application.

In order to select an appropriate cache size for lrucache, the following factors should be considered, for example:

How much memory can your device allocate for each application?

How many pictures can be displayed on the device screen at a time?How many images need to be preloaded because they may be displayed on the screen soon?

What is the screen size and resolution of your device?A super-high resolution device (such as Galaxy nexus) needs more cache space than a lower resolution device (such as nexus s) when holding the same number of images.

The size and size of the image, and how much memory space each image will occupy.

How often are images visited?Will some pictures be visited more frequently than others?If so, you may want to keep some images resident in memory, or use multiple lrucache objects to distinguish different groups of images.

Can you keep the balance between quantity and quality?Sometimes, it’s more effective to store multiple low pixel images, but it’s more effective to load high pixel images in the background.

There is no specified cache size for all applications, which is up to you. You should analyze the memory usage of the program, and then work out an appropriate solution. A too small cache space may cause images to be released and reloaded frequently, which is not good. However, if the cache space is too large, it may still cause problems java.lang.OutOfMemory It’s abnormal.

Here is an example of using lrucache to cache images:

private LruCache<String, Bitmap> mMemoryCache;  
@Override
protected void onCreate(Bundle savedInstanceState) { 
    // Get the maximum value of available memory, using memory beyond this value will raise an OutOfMemory exception. 
    // LruCache passes in the cache value in KB through the constructor. 
    int maxMemory = (int) (Runtime.getRuntime().maxMemory() /1024); 
    // Use 1/8 of the maximum available memory value as the size of the cache. 
    int cacheSize = maxMemory/8; 
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { 
        @Override
        protected int sizeOf(String key, Bitmap bitmap) { 
            // Override this method to measure the size of each image and return the number of images by default. 
            return bitmap.getByteCount()/1024; 
        } 
    }; 
} 

public void addBitmapToMemoryCache(String key, Bitmap bitmap) { 
    if (getBitmapFromMemCache(key) == null) { 
        mMemoryCache.put(key, bitmap); 
    } 
} 

public Bitmap getBitmapFromMemCache(String key) { 
    return mMemoryCache.get(key); 
}

In this example, one eighth of the memory allocated by the system to the application is used as the cache size. In medium and high configuration mobile phones, there will be about 4 megabytes (32g8) of cache space. If a full screen GridView is filled with four 800×480 resolution images, it will occupy about 1.5 megabytes of space (800 * 480 * 4). Therefore, this cache size can store 2.5 pages of images.

When a picture is loaded into ImageView, it will be checked in the cache of lrucache first. If the corresponding key value is found, the ImageView will be updated immediately. Otherwise, a background thread will be started to load the image.

public void loadBitmap(int resId, ImageView imageView) { 
    final String imageKey = String.valueOf(resId); 
    final Bitmap bitmap = getBitmapFromMemCache(imageKey); 
    if (bitmap != null) { 
        imageView.setImageBitmap(bitmap); 
    } else { 
        imageView.setImageResource(R.drawable.image_placeholder); 
        BitmapWorkerTask task = new BitmapWorkerTask(imageView); 
        task.execute(resId); 
    } 
}

Bitmapworkertask also puts the key value pair of the newly loaded image into the cache.

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> { 
    // loading the pictures
    @Override
    protected Bitmap doInBackground(Integer... params) { 
        final Bitmap bitmap = decodeSampledBitmapFromResource( 
                getResources(), params[0], 100, 100); 
        addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); 
        return bitmap; 
    } 
}

(how to define the key of image key value pair?Path to image (URI)

What are the common memory leaks in Android

Query database without closing cursor

In Android, Cursor is a very common object, but in writing code, people often forget to call close, or because of the code logic problem situation, close is not called.

Usually, in an activity, we can call startmanagingcursor or directly use managedquery to let the activity automatically manage the cursor object.
However, it should be noted that when activity is introduced, cursor will no longer be available!
If the code of operating cursor is not synchronized with UI (such as background thread), there is no need to judge whether the activity has ended or wait for the background thread to end before calling ondestroy.
In addition, the following is also a common case that the cursor will not be closed:
although it seems that, Cursor.close () has been called, but if there is an exception, close () will be skipped, resulting in a memory leak.
Therefore, our code should be written in the following way:

Cursor c = queryCursor(); 
try { 
int a = c.getInt(1); 
...... 
} catch (Exception e) { 
} finally { 
c.close(); //Call close() in finally, ensuring that it will be called 
} 
try { 
Cursor c = queryCursor(); 
int a = c.getInt(1); 
...... 
c.close(); 
} catch (Exception e) { 
} 

Unregisterreceiver() was not called after calling registerreceiver

After calling registerreceiver, if unregisterreceiver is not called, it will occupy a large amount of memory.
We can often see the following code:
this is a very serious error, because it will cause the broadcastreceiver not to be unregistered, resulting in memory leakage.

registerReceiver(new BroadcastReceiver() { 
... 
}, filter); ... 

*InputStream/OutputStream not closed*

When using files or accessing network resources, using InputStream/OutputStream will also lead to memory leakage

Recycle () is not called after bitmap is used
according to the description of SDK, it is not necessary to call recycle. However, when we call recycle (), we no longer use memory as much as possible.

Context leak
this is a very obscure memory leak.
Let’s take a look at the following code:
in this code, we use a static drawable object.
This usually happens when we need to call a drawable frequently, and its loading is time-consuming. We don’t want to create the drawable every time we load an activity.
At this point, using static is undoubtedly the fastest way to write code, but it is also very bad.
When a drawable is attached to a view, the view will be set to the callback of the drawable Drawable.setCallback () Implementation).
This means that the drawable has a reference to textview, which in turn has a reference to activity.
As a result, the memory will not be released after the activity is destroyed.

Vs generated an error: “error LNK 1168: unable to open xxxxxx.exe Write to

When writing C + + code with VS, you often encounter this situation when you finish writing the code generation project: “error LNK 1168: unable to open xxxxxx.exe Write.

 

There are three solutions (the first two are temporary but not permanent, and the third is radical)

1. Do nothing, wait for a moment, about a few minutes, you can successfully generate.

2. Delete the. EXE file generated in the previous debug folder, and it will be generated successfully.

3. The most fundamental way: open the control panel – & gt; management tools – & gt; Services – & gt; to enable the application experience service.