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

