Chapter 7: Compiling C++ Sources with CMake_《Modern CMake for C++》_Notes

Chapter 7: Compiling C++ Sources with CMake


1. Understanding the Compilation Process

Key Points:

  • Four-stage process: Preprocessing → Compilation → Assembly → Linking
  • CMake abstracts low-level commands but allows granular control
  • Toolchain configuration (compiler flags, optimizations, diagnostics)

Code Example - Basic Compilation Flow:

add_executable(MyApp main.cpp util.cpp)

2. Preprocessor Configuration

a. Include Directories

target_include_directories(MyAppPRIVATE src/${PROJECT_BINARY_DIR}/generated
)

b. Preprocessor Definitions

target_compile_definitions(MyAppPRIVATEDEBUG_MODE=1"PLATFORM_NAME=\"Linux\""
)

Key Considerations:

  • Use PRIVATE/PUBLIC/INTERFACE appropriately
  • Avoid manual -D flags; prefer CMake’s abstraction

3. Optimization Configuration

a. General Optimization Levels

target_compile_options(MyAppPRIVATE$<$<CONFIG:RELEASE>:-O3>$<$<CONFIG:DEBUG>:-O0>
)

b. Specific Optimizations

target_compile_options(MyAppPRIVATE-funroll-loops-ftree-vectorize
)

Key Considerations:

  • Use generator expressions for build-type-specific flags
  • Test optimization compatibility with check_cxx_compiler_flag()

4. Compilation Time Reduction

a. Precompiled Headers (PCH)

target_precompile_headers(MyAppPRIVATE<vector><string>common.h
)

b. Unity Builds

set(CMAKE_UNITY_BUILD ON)
set(CMAKE_UNITY_BUILD_BATCH_SIZE 50)
add_executable(MyApp UNITY_GROUP_SOURCES src/*.cpp)

Tradeoffs:

  • PCH: Faster compilation but larger memory usage
  • Unity Builds: Reduced link time but harder debugging

5. Diagnostics Configuration

a. Warnings & Errors

target_compile_options(MyAppPRIVATE-Wall-Werror-Wno-deprecated-declarations
)

b. Cross-Compiler Compatibility

include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-Wconversion HAS_WCONVERSION)
if(HAS_WCONVERSION)target_compile_options(MyApp PRIVATE -Wconversion)
endif()

Best Practices:

  • Treat warnings as errors in CI builds
  • Use compiler-agnostic warning flags (/W4 vs -Wall)

6. Debug Information
target_compile_options(MyAppPRIVATE$<$<CONFIG:DEBUG>:-g3>$<$<CXX_COMPILER_ID:MSVC>:/Zi>
)

Key Considerations:

  • -g (GCC/Clang) vs /Zi (MSVC)
  • Separate debug symbols (-gsplit-dwarf for GCC)

7. Advanced Features

a. Link Time Optimization (LTO)

include(CheckIPOSupported)
check_ipo_supported(RESULT ipo_supported)
if(ipo_supported)set_target_properties(MyApp PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()

b. Platform-Specific Flags

if(CMAKE_SYSTEM_PROCESSOR MATCHES "arm")target_compile_options(MyApp PRIVATE -mfpu=neon)
endif()

8. Common Pitfalls & Solutions

Problem: Inconsistent flags across targets
Solution: Use add_compile_options() carefully, prefer target-specific commands

Problem: Debug symbols missing in Release builds
Solution:

set(CMAKE_BUILD_TYPE RelWithDebInfo)

Problem: Compiler-specific flags breaking cross-platform builds
Solution: Use CMake’s abstraction:

target_compile_features(MyApp PRIVATE cxx_std_20)

9. Complete Example
cmake_minimum_required(VERSION 3.20)
project(OptimizedApp)# Compiler feature check
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag(-flto HAS_LTO)# Executable with unified build
add_executable(MyApp [UNITY_GROUP_SOURCES]src/main.cpp src/utils.cpp
)# Precompiled headers
target_precompile_headers(MyApp PRIVATE common.h)# Includes & definitions
target_include_directories(MyAppPRIVATEinclude/${CMAKE_CURRENT_BINARY_DIR}/gen
)target_compile_definitions(MyAppPRIVATEAPP_VERSION=${PROJECT_VERSION}
)# Optimization & diagnostics
target_compile_options(MyAppPRIVATE$<$<CONFIG:Release>:-O3 -flto>$<$<CONFIG:Debug>:-O0 -g3>-Wall-Werror
)# LTO configuration
if(HAS_LTO)set_target_properties(MyApp PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()

Key Takeaways
  1. Target-Specific Commands > Global settings
  2. Generator Expressions enable conditional logic
  3. Compiler Abstraction ensures portability
  4. Diagnostic Rigor prevents runtime errors
  5. Build-Type Awareness (Debug/Release) is crucial

Multiple Choice Questions


Question 1: Compilation Stages
Which of the following are required stages in the C++ compilation process when using CMake?
A) Preprocessing
B) Linking
C) Assembly
D) Code generation
E) Static analysis


Question 2: Preprocessor Configuration
Which CMake commands are valid for configuring the preprocessor?
A) target_include_directories()
B) add_definitions(-DDEBUG)
C) target_compile_definitions()
D) include_directories()
E) target_link_libraries()


Question 3: Header File Management
Which CMake features help manage header files correctly?
A) Using target_include_directories() with the PUBLIC keyword
B) Manually copying headers to the build directory
C) Using configure_file() to generate versioned headers
D) Adding headers to add_executable()/add_library() commands
E) Using file(GLOB) to collect headers


Question 4: Optimizations
Which optimization techniques can be controlled via CMake?
A) Function inlining (-finline-functions)
B) Loop unrolling (-funroll-loops)
C) Link-Time Optimization (-flto)
D) Setting -O3 as the default optimization level
E) Disabling exceptions via -fno-exceptions


Question 5: Reducing Compilation Time
Which CMake mechanisms are valid for reducing compilation time?
A) Enabling precompiled headers with target_precompile_headers()
B) Using UNITY_BUILD to merge source files
C) Disabling RTTI via -fno-rtti
D) Enabling ccache via CMAKE_<LANG>_COMPILER_LAUNCHER
E) Setting CMAKE_BUILD_TYPE=Debug


Question 6: Debugging Configuration
Which CMake settings are essential for generating debuggable binaries?
A) add_compile_options(-g)
B) set(CMAKE_BUILD_TYPE Debug)
C) target_compile_definitions(DEBUG)
D) Enabling -O0 optimization
E) Using -fsanitize=address


Question 7: Precompiled Headers
Which practices ensure correct usage of precompiled headers (PCH) in CMake?
A) Including PCH as the first header in source files
B) Using target_precompile_headers() with PRIVATE scope
C) Adding all headers to the PCH
D) Avoiding PCH for template-heavy code
E) Manually compiling headers with -x c++-header


Question 8: Error/Warning Flags
Which CMake commands enforce strict error handling?
A) add_compile_options(-Werror)
B) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
C) target_compile_options(-Wpedantic)
D) cmake_minimum_required(VERSION 3.10)
E) include(CheckCXXCompilerFlag)


Question 9: Platform-Specific Compilation
Which CMake variables detect platform-specific properties?
A) CMAKE_SYSTEM_NAME
B) CMAKE_CXX_COMPILER_ID
C) CMAKE_HOST_SYSTEM_PROCESSOR
D) CMAKE_SOURCE_DIR
E) CMAKE_ENDIANNESS


Question 10: Compiler Feature Detection
Which CMake modules/commands help check compiler support for C++ features?
A) check_cxx_compiler_flag()
B) include(CheckCXXSourceCompiles)
C) target_compile_features()
D) find_package(CXX17)
E) try_compile()


Answers & Explanations


Question 1: Compilation Stages
Correct Answers: A, C

  • A) Preprocessing and C) Assembly are core stages.
  • B) Linking occurs after compilation (handled separately).
  • D) Code generation is part of the compilation stage.
  • E) Static analysis is optional and not a standard stage.

Question 2: Preprocessor Configuration
Correct Answers: A, C

  • A) target_include_directories() sets include paths.
  • C) target_compile_definitions() adds preprocessor macros.
  • B/D) add_definitions() and include_directories() are legacy (not target-specific).
  • E) target_link_libraries() handles linking, not preprocessing.

Question 3: Header File Management
Correct Answers: A, C

  • A) target_include_directories(PUBLIC) propagates include paths.
  • C) configure_file() generates headers (e.g., version info).
  • B/D/E) Manual copying, add_executable(), or file(GLOB) are error-prone.

Question 4: Optimizations
Correct Answers: A, B, C

  • A/B/C) Explicitly controlled via target_compile_options().
  • D) -O3 is compiler-specific; CMake uses CMAKE_BUILD_TYPE (e.g., Release).
  • E) Disabling exceptions is a language feature, not an optimization.

Question 5: Reducing Compilation Time
Correct Answers: A, B, D

  • A/B) PCH and Unity builds reduce redundant parsing.
  • D) ccache caches object files.
  • C/E) Disabling RTTI/Debug builds do not reduce compilation time directly.

Question 6: Debugging Configuration
Correct Answers: A, B, D

  • A/B/D) -g, Debug build type, and -O0 ensure debuggable binaries.
  • C) DEBUG is a preprocessor macro (not required for symbols).
  • E) Sanitizers aid debugging but are not strictly required.

Question 7: Precompiled Headers
Correct Answers: A, B

  • A) PCH must be included first to avoid recompilation.
  • B) PRIVATE limits PCH to the current target.
  • C/E) Including all headers or manual compilation breaks portability.
  • D) PCH works with templates but may increase build complexity.

Question 8: Error/Warning Flags
Correct Answers: A, B, C

  • A/B/C) Enforce warnings/errors via compiler flags.
  • D/E) cmake_minimum_required() and CheckCXXCompilerFlag are unrelated to error handling.

Question 9: Platform-Specific Compilation
Correct Answers: A, B, C

  • A/B/C) Detect OS, compiler, and architecture.
  • D) CMAKE_SOURCE_DIR is the project root.
  • E) CMAKE_ENDIANNESS is not a standard CMake variable.

Question 10: Compiler Feature Detection

Correct Answers: A, B, E

  • A/B/E) Directly check compiler support for flags/features.
  • C) target_compile_features() specifies required standards.
  • D) CXX17 is not a standard package.

Practice Questions


Question 1: Preprocessor Definitions & Conditional Compilation
Scenario:
You’re working on a cross-platform project where a DEBUG_MODE macro must be defined only in Debug builds, and a PLATFORM_WINDOWS macro should be defined automatically when compiling on Windows. Additionally, in Release builds, the NDEBUG macro must be enforced.

Task:
Write a CMake snippet to configure these preprocessor definitions correctly for a target my_app, using modern CMake practices. Handle platform detection and build type conditions appropriately.


Question 2: Precompiled Headers (PCH)
Scenario:
Your project has a frequently used header common.h that includes heavy template code. To speed up compilation, you want to precompile this header for a target my_lib. However, your team uses both GCC/Clang and MSVC compilers.

Task:
Configure CMake to generate a PCH for common.h and apply it to my_lib, ensuring compatibility across GCC, Clang, and MSVC. Avoid hardcoding compiler-specific flags.


Hard Difficulty Question: Unity Builds & Platform-Specific Optimizations
Scenario:
A large project suffers from long compilation times. You decide to implement Unity Builds (combining multiple .cpp files into a single compilation unit) for a target big_target, while also enabling Link-Time Optimization (LTO) in Release builds. Additionally, on Linux, you want to enforce -march=native, but on Windows, use /arch:AVX2.

Task:

  1. Configure CMake to enable Unity Builds for big_target by grouping all .cpp files in src/ into batches of 10 files.
  2. Enable LTO in Release builds using CMake’s built-in support.
  3. Apply architecture-specific optimizations conditionally based on the platform.
  4. Ensure the solution avoids file(GLOB) anti-patterns and uses generator expressions where appropriate.

Answers & Explanations


Answer to Medium Question 1

target_compile_definitions(my_appPRIVATE$<$<CONFIG:Debug>:DEBUG_MODE>$<$<PLATFORM_ID:Windows>:PLATFORM_WINDOWS>PUBLIC$<$<CONFIG:Release>:NDEBUG>
)

Explanation:

  • Conditional Definitions:
    • Use generator expressions ($<...>) to conditionally define macros based on build type (CONFIG) and platform (PLATFORM_ID).
    • $<$<CONFIG:Debug>:DEBUG_MODE> adds -DDEBUG_MODE only in Debug builds.
    • $<$<PLATFORM_ID:Windows>:PLATFORM_WINDOWS> automatically defines PLATFORM_WINDOWS on Windows.
  • Public vs Private:
    • NDEBUG is marked PUBLIC to propagate to dependent targets (e.g., if my_app is a library).
    • Platform-specific and build-type-specific flags are PRIVATE to avoid leaking to dependents.

Answer to Medium Question 2

# Enable precompiled headers for the target
target_precompile_headers(my_libPRIVATE# For GCC/Clang: Use the header directly$<$<CXX_COMPILER_ID:GNU,Clang>:common.h># For MSVC: Use forced include$<$<CXX_COMPILER_ID:MSVC>:/FIcommon.h>
)# MSVC requires the header to be part of the source tree
if(MSVC)target_sources(my_lib PRIVATE common.h)
endif()

Explanation:

  • Compiler-Agnostic PCH:
    • target_precompile_headers is the modern CMake way to handle PCH.
    • For GCC/Clang, specifying common.h directly tells CMake to precompile it.
    • MSVC requires /FI (Force Include) to use the PCH, hence the generator expression.
  • MSVC Workaround:
    • MSVC needs the header in the source list to avoid “header not found” errors.
  • No Hardcoded Flags:
    • Avoids manual -Winvalid-pch or /Yc//Yu flags by relying on CMake abstractions.

Answer to Hard Question

# 1. Unity Build Configuration
file(GLOB_RECURSE SRC_FILES CONFIGURE_DEPENDS src/*.cpp)
set(BATCH_SIZE 10)
set(UNITY_SOURCES "")
math(EXPR N_BATCHES "${SRC_FILES} / ${BATCH_SIZE} + 1")foreach(BATCH RANGE 1 ${N_BATCHES})list(SUBLIST SRC_FILES ${BATCH_SIZE}*(BATCH-1) ${BATCH_SIZE} BATCH_FILES)if(BATCH_FILES)set(UNITY_FILE "unity_${BATCH}.cpp")file(WRITE ${UNITY_FILE} "")foreach(SRC ${BATCH_FILES})file(APPEND ${UNITY_FILE} "#include \"${SRC}\"\n")endforeach()list(APPEND UNITY_SOURCES ${UNITY_FILE})endif()
endforeach()add_library(big_target ${UNITY_SOURCES})# 2. LTO in Release
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE ON)# 3. Platform-Specific Optimizations
target_compile_options(big_targetPRIVATE$<$<AND:$<PLATFORM_ID:Linux>,$<CONFIG:Release>>:-march=native>$<$<AND:$<PLATFORM_ID:Windows>,$<CONFIG:Release>>:/arch:AVX2>
)

Explanation:

  1. Unity Builds:
    • file(GLOB_RECURSE ... CONFIGURE_DEPENDS) avoids the “stale file list” anti-pattern by re-globbing on build system regeneration.
    • Batches .cpp files into unity_X.cpp files, each including 10 source files.
    • Note: Unity builds trade compilation speed for incremental build efficiency. Use judiciously.
  2. LTO:
    • CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE enables LTO portably across compilers.
  3. Platform-Specific Flags:
    • Uses nested generator expressions to apply -march=native on Linux and /arch:AVX2 on Windows only in Release builds.
  4. Best Practices:
    • Avoids file(GLOB) for source lists in most cases but uses CONFIGURE_DEPENDS to mitigate its drawbacks here.
    • Generator expressions ensure flags are applied conditionally without polluting other configurations/platforms.

Key Concepts from Chapter 7 Reinforced:

  1. Generator Expressions: Used extensively for conditional logic based on build type, platform, and compiler.
  2. Precompiled Headers: Leveraged via target_precompile_headers with compiler-specific logic abstracted by CMake.
  3. Build Optimization: Unity builds and LTO demonstrate advanced techniques to reduce compilation time.
  4. Platform/Compiler Portability: Solutions avoid hardcoding flags, using CMake variables (PLATFORM_ID, CXX_COMPILER_ID) instead.
  5. Modern CMake Practices: Use of target_* commands ensures properties propagate correctly to dependents.

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/77054.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/77054.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/77054.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

5分鐘上手GitHub Copilot:AI編程助手實戰指南

引言 近年來&#xff0c;AI編程工具逐漸成為開發者提升效率的利器。GitHub Copilot作為由GitHub和OpenAI聯合推出的智能代碼補全工具&#xff0c;能夠根據上下文自動生成代碼片段。本文將手把手教你如何快速安裝、配置Copilot&#xff0c;并通過實際案例展示其強大功能。 一、…

謝志輝和他的《韻之隊詩集》:探尋生活與夢想交織的詩意世界

大家好&#xff0c;我是謝志輝&#xff0c;一個扎根在文字世界&#xff0c;默默耕耘的寫作者。寫作于我而言&#xff0c;早已不是簡單的愛好&#xff0c;而是生命中不可或缺的一部分。無數個寂靜的夜晚&#xff0c;當世界陷入沉睡&#xff0c;我獨自坐在書桌前&#xff0c;伴著…

Logo語言的死鎖

Logo語言的死鎖現象研究 引言 在計算機科學中&#xff0c;死鎖是一個重要的研究課題&#xff0c;尤其是在并發編程中。它指的是兩個或多個進程因爭奪資源而造成的一種永久等待狀態。在編程語言的設計與實現中&#xff0c;如何避免死鎖成為了優化系統性能和提高程序可靠性的關…

深入理解矩陣乘積的導數:以線性回歸損失函數為例

深入理解矩陣乘積的導數&#xff1a;以線性回歸損失函數為例 在機器學習和數據分析領域&#xff0c;矩陣微積分扮演著至關重要的角色。特別是當我們涉及到優化問題&#xff0c;如最小化損失函數時&#xff0c;對矩陣表達式求導變得必不可少。本文將通過一個具體的例子——線性…

real_time_camera_audio_display_with_animation

視頻錄制 import cv2 import pyaudio import wave import threading import os import tkinter as tk from PIL import Image, ImageTk # 視頻錄制設置 VIDEO_WIDTH = 640 VIDEO_HEIGHT = 480 FPS = 20.0 VIDEO_FILENAME = _video.mp4 AUDIO_FILENAME = _audio.wav OUTPUT_…

【Pandas】pandas DataFrame astype

Pandas2.2 DataFrame Conversion 方法描述DataFrame.astype(dtype[, copy, errors])用于將 DataFrame 中的數據轉換為指定的數據類型 pandas.DataFrame.astype pandas.DataFrame.astype 是一個方法&#xff0c;用于將 DataFrame 中的數據轉換為指定的數據類型。這個方法非常…

Johnson

理論 全源最短路算法 Floyd 算法&#xff0c;時間復雜度為 O(n)跑 n 次 Bellman - Ford 算法&#xff0c;時間復雜度是 O(nm)跑 n 次 Heap - Dijkstra 算法&#xff0c;時間復雜度是 O(nmlogm) 第 3 種算法被 Johnson 做了改造&#xff0c;可以求解帶負權邊的全源最短路。 J…

Exce格式化批處理工具詳解:高效處理,讓數據更干凈!

Exce格式化批處理工具詳解&#xff1a;高效處理&#xff0c;讓數據更干凈&#xff01; 1. 概述 在數據分析、報表整理、數據庫管理等工作中&#xff0c;數據清洗是不可或缺的一步。原始Excel數據常常存在格式不統一、空值、重復數據等問題&#xff0c;影響數據的準確性和可用…

(三十七)Dart 中使用 Pub 包管理系統與 HTTP 請求教程

Dart 中使用 Pub 包管理系統與 HTTP 請求教程 Pub 包管理系統簡介 Pub 是 Dart 和 Flutter 的包管理系統&#xff0c;用于管理項目的依賴。通過 Pub&#xff0c;開發者可以輕松地添加、更新和管理第三方庫。 使用 Pub 包管理系統 1. 找到需要的庫 訪問以下網址&#xff0c…

代碼隨想錄算法訓練營第三十五天 | 416.分割等和子集

416. 分割等和子集 題目鏈接&#xff1a;416. 分割等和子集 - 力扣&#xff08;LeetCode&#xff09; 文章講解&#xff1a;代碼隨想錄 視頻講解&#xff1a;動態規劃之背包問題&#xff0c;這個包能裝滿嗎&#xff1f;| LeetCode&#xff1a;416.分割等和子集_嗶哩嗶哩_bilibi…

HTTP 教程 : 從 0 到 1 全面指南 教程【全文三萬字保姆級詳細講解】

目錄 HTTP 的請求-響應 HTTP 方法 HTTP 狀態碼 HTTP 版本 安全性 HTTP/HTTPS 簡介 HTTP HTTPS HTTP 工作原理 HTTPS 作用 HTTP 與 HTTPS 區別 HTTP 消息結構 客戶端請求消息 服務器響應消息 實例 HTTP 請求方法 各個版本定義的請求方法 HTTP/1.0 HTTP/1.1 …

spring功能匯總

1.創建一個dao接口&#xff0c;實現類&#xff1b;service接口&#xff0c;實現類并且service里用new創建對象方式調用dao的方法 2.使用spring分別獲取dao和service對象(IOC) 注意 2中的service里面獲取dao的對象方式不用new的(DI) 運行測試&#xff1a; 使用1的方式創建servic…

Vue.js 實現下載模板和導入模板、數據比對功能核心實現。

在前端開發中&#xff0c;數據比對是一個常見需求&#xff0c;尤其在資產管理等場景中。本文將基于 Vue.js 和 Element UI&#xff0c;通過一個簡化的代碼示例&#xff0c;展示如何實現“新建比對”和“開始比對”功能的核心部分。 一、功能簡介 我們將聚焦兩個核心功能&…

volatile關鍵字用途說明

volatile 關鍵字在 C# 中用于指示編譯器和運行時系統&#xff0c;某個字段可能會被多個線程同時訪問&#xff0c;并且該字段的讀寫操作不應被優化&#xff08;例如緩存到寄存器或重排序&#xff09;&#xff0c;以確保所有線程都能看到最新的值。這使得 volatile 成為一種輕量級…

【區塊鏈安全 | 第三十五篇】溢出漏洞

文章目錄 溢出上溢示例溢出漏洞溢出示例漏洞代碼代碼審計1. deposit 函數2. increaseLockTime 函數 攻擊代碼攻擊過程總結修復建議審計思路 溢出 算術溢出&#xff08;Arithmetic Overflow&#xff09;&#xff0c;簡稱溢出&#xff08;Overflow&#xff09;&#xff0c;通常分…

百度的deepseek與硅基模型的差距。

問題&#xff1a; 已經下載速度8兆每秒&#xff0c;請問下載30G的文件需要多長時間&#xff1f; 關于這個問題。百度的回答如下&#xff1a; ?30GB文件下載時間計算? ?理論計算?&#xff08;基于十進制單位&#xff09;&#xff1a; ?單位換算? 文件大小&#xff1a;3…

車載診斷架構 --- 特殊定義NRC處理原理

我是穿拖鞋的漢子,魔都中堅持長期主義的汽車電子工程師。 老規矩,分享一段喜歡的文字,避免自己成為高知識低文化的工程師: 周末洗了一個澡,換了一身衣服,出了門卻不知道去哪兒,不知道去找誰,漫無目的走著,大概這就是成年人最深的孤獨吧! 舊人不知我近況,新人不知我過…

面試題ing

1、js中set和map的作用和區別? 在 JavaScript 中&#xff0c;Set 和 Map 是兩種非常重要的集合類型 1、Set 是一種集合數據結構&#xff0c;用于存儲唯一值。它類似于數組&#xff0c;但成員的值都是唯一的&#xff0c;沒有重復的值。Set 中的值只能是唯一的&#xff0c;任何…

Python爬蟲第6節-requests庫的基本用法

目錄 前言 一、準備工作 二、實例引入 三、GET請求 3.1 基本示例 3.2 抓取網頁 3.3 抓取二進制數據 3.4 添加headers 四、POST請求 五、響應 前言 前面我們學習了urllib的基礎使用方法。不過&#xff0c;urllib在實際應用中存在一些不便之處。以網頁驗證和Cookies處理…

Go 學習筆記 · 進階篇 · 第一天:接口與多態

&#x1f436;Go接口與多態&#xff1a;繼承沒了&#xff0c;但自由炸裂&#xff01; 最近翻 Go 的代碼&#xff0c;突然看到這么一段&#xff1a; type Animal interface {Speak() string }我一愣&#xff0c;咦&#xff1f;這不就是 Java 里常見的“接口”嗎&#xff1f; …