You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CMake如何深度复制字符串列表?避免修改原列表

Fix: Modifying copied list affects original in CMake

Ah, I see the issue here—it's not about references vs deep copies, but a simple syntax mistake in how you're copying the list. You're not actually duplicating the content of ${TARGET_NAME}_SRC_FILES into NEW_LIST; instead, you're storing the name of the original variable in NEW_LIST, so all your subsequent operations are still targeting the original list.

Why your code is modifying the original list

Look at this line:

set(NEW_LIST ${TARGET_NAME}_SRC_FILES)

This sets NEW_LIST to the string "${TARGET_NAME}_SRC_FILES" (e.g., if TARGET_NAME is MyApp, NEW_LIST becomes MyApp_SRC_FILES). When you use ${NEW_LIST} later, CMake expands it to the original variable name, so list(REMOVE_ITEM ${NEW_LIST} ...) is equivalent to list(REMOVE_ITEM ${TARGET_NAME}_SRC_FILES ...)—you're directly modifying the original list!

How to correctly copy the list

To create a true copy of the original list's contents, you need to expand the original variable first and assign its value to NEW_LIST. Wrap the expanded variable in quotes to preserve list structure (especially important if your files have spaces):

# Properly copy the original list into NEW_LIST
set(NEW_LIST "${${TARGET_NAME}_SRC_FILES}")

message("new list content1 : ${NEW_LIST}")
list(REMOVE_ITEM NEW_LIST ${${TARGET_NAME}_LIN64_EXCLUDED_SRC_FILES})
message("new list content2 : ${NEW_LIST}")
message("original list content: ${${TARGET_NAME}_SRC_FILES}")

Now NEW_LIST holds an independent copy of the original list. Modifying NEW_LIST won't touch ${TARGET_NAME}_SRC_FILES anymore.

A quick note on CMake lists

CMake treats lists as semicolon-separated strings. Wrapping the expanded variable in quotes ensures that the semicolon-separated structure is preserved during assignment, so you don't accidentally split list elements if they contain spaces.

内容的提问来源于stack exchange,提问作者Xavier Bigand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:23:44