CMake变量的作用域

You need to use set instead of list to affect the variable in the parent scope.

So replace your list command with:

set(source_list ${source_list} ${file_path} PARENT_SCOPE)
shareimprove this answer
30k44 gold badges3636 silver badges6868 bronze badges
answered Apr 5 '12 at 16:25
53.9k1010 gold badges176176 silver badges184184 bronze badges
  • 1

    It's not global though, siblings will not see. – 0xbaadf00d Apr 4 '17 at 6:32


  • @JoachimW: Why incorporate two answers into the single one? You seems to misunderstand Question/Answer model on Stack Overflow. We do NOT tend to have all solutions in the single accepted answer. Instead, having one answer per solution is perfect. And an answer's quality is primarily measured by the voting, good answers needn't to be marked with the green accept mark. Please, revert this answers merging. – Tsyvarev Oct 1 '18 at 10:37 
16

PARENT_SCOPE is only for parent, it won't work if you have other non-parent script that want to see it as well.

You need cache for the true "global-like" variable. In your case, use:

SET(source_list  "${source_list}" CACHE INTERNAL "source_list")
shareimprove this answer
answered Aug 5 '14 at 3:05
1,3821717 silver badges2121 bronze badges
8

Another approach is to use global properties. Once you set it:

set_property(GLOBAL PROPERTY source_list_property "${source_list}")

you can read it from everywhere:

get_property(source_list GLOBAL PROPERTY source_list_property)

I used in examples above the different names for property (source_list_property) and for variable (source_list). Maybe it is better to use the same name. But point is to use a property as global variables, and not about naming.

Such global properties aren't in cache.


原文地址:https://www.cnblogs.com/lizhensheng/p/11117247.html