# Using generator expression with add\_library

**URL:** https://discourse.cmake.org/t/using-generator-expression-with-add-library/156
**Category:** Code
**Created:** [November 7, 2019, 11:02am UTC](https://discourse.cmake.org/t/using-generator-expression-with-add-library/156 "2019-11-07T11:02:48Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![DavidA](https://discourse.cmake.org/user_avatar/discourse.cmake.org/davida/32/128_2.png) [@DavidA](https://discourse.cmake.org/u/DavidA)
#### Post date: [November 7, 2019, 11:02am UTC](https://discourse.cmake.org/t/using-generator-expression-with-add-library/156/1 "2019-11-07T11:02:48Z")

</div>

I want to build a shared library for Linux and a static library for Windows. So I have tried:

```
 set (_star_lib_name "StdStars")
 
 add_library(${_star_lib_name} 
             $<$<CXX_COMPILER_ID:GNU>:SHARED>
             $<$<CXX_COMPILER_ID:MSVC>:STATIC> 
             ""
 )

```

but that gives me error:

```
CMake Error at C:/SVNProj/zodiac/branches/TRY_TML_CMake_3Oct2019/StarLibs/StdStars/CMakeLists.txt:7 (add_library):
Cannot find source file:

    STATIC

  Tried extensions .c .C .c++ .cc .cpp .cxx .cu .m .M .mm .h .hh .h++ .hm
  .hpp .hxx .in .txx

```

What is the correct way of doing this?

---

<div class="post-metadata">

### Author: ![kyle.edwards](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/k/65b543/32.png) [@kyle.edwards](https://discourse.cmake.org/u/kyle.edwards)
#### Post date: [November 7, 2019, 2:19pm UTC](https://discourse.cmake.org/t/using-generator-expression-with-add-library/156/2 "2019-11-07T14:19:50Z")

</div>

`add_library()` has to know the library type at configure-time - trying to change it with a generator expression won’t work. Try this instead:

```cmake
if(MSVC)
  set(_type STATIC)
else()
  set(_type SHARED)
endif()
add_library(StdStars ${_type}
  # sources here
  )

```

---

<div class="post-metadata">

### Author: ![DavidA](https://discourse.cmake.org/user_avatar/discourse.cmake.org/davida/32/128_2.png) [@DavidA](https://discourse.cmake.org/u/DavidA)
#### Post date: [November 14, 2019, 8:57am UTC](https://discourse.cmake.org/t/using-generator-expression-with-add-library/156/3 "2019-11-14T08:57:17Z")

</div>

Thanks for your answer.
