# test case for internal library (PUBLIC and PRIVATE)

**URL:** <https://discourse.cmake.org/t/test-case-for-internal-library-public-and-private/12707>\
**Category:** Code\
**Tags:** os:windows\
**Created:** [October 8, 2024, 7:04am UTC](https://discourse.cmake.org/t/test-case-for-internal-library-public-and-private/12707 "2024-10-08T07:04:47Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sea\_Sea](https://discourse.cmake.org/user_avatar/discourse.cmake.org/sea_sea/32/4025_2.png) [@Sea\_Sea](https://discourse.cmake.org/u/Sea_Sea)\
**Post date:** [October 8, 2024, 7:04am UTC](https://discourse.cmake.org/t/test-case-for-internal-library-public-and-private/12707/1 "2024-10-08T07:04:47Z")

</div>

I reference two project and add some dependent library.  
The cmake tell us that using `PRIVATE` to protect our code

> **[GitHub - pablospe/cmake-example-library: How to install a library with cmake](https://github.com/pablospe/cmake-example-library)**
>
> How to install a library with cmake

> **[GitHub - gabime/spdlog: Fast C++ logging library.](https://github.com/gabime/spdlog)**
>
> Fast C++ logging library.

# Background

main project `bar `  
`foo` library

The `bar` execution will use the `foo` library  
where `foo` use `spdlog` third party

# Test case

### test 1 .

PASS

```auto
# foo cmake
target_link_libraries(foo PRIVATE spdlog::spdlog)

target_include_directories(
  foo PUBLIC
    "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>"
     ...
)

```

```auto
# foo.cpp
#include <spdlog/spdlog.h>

```

### test 2.

Fail

```auto
# foo cmake
target_link_libraries(foo PRIVATE spdlog::spdlog)

target_include_directories(
  foo PUBLIC
    "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>"
     ...
)

```

```auto
# foo.h
#include <spdlog/spdlog.h>

```

```auto
# error
can not open "spdlog/spdlog.h"

```

### test 3.

PASS

```auto
# foo cmake
target_link_libraries(foo PUBLIC spdlog::spdlog)

target_include_directories(
  foo PUBLIC
    "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>"
     ...
)

```

```auto
# foo.h
#include <spdlog/spdlog.h>

```

### test 4

PASS

```auto
# foo cmake
target_link_libraries(foo PRIVATE spdlog::spdlog)

target_include_directories(
  foo PUBLIC
    "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}>"
     ...
    "$<BUILD_INTERFACE:${SPDLOG_INCLUDE_DIRS}>"
)

```

```auto
# foo.h
#include <spdlog/spdlog.h>

```

# Question

In modern camke, we always use the imported target to link my program, so we don’t need to target\_link\_libraries. And cmake always suggest our code should be PRIVATE.

1. Why does Test 1 work?

2. When is the best time to use PRIVATE to protect code?

3. Shall I always use PUBLIC for target\_link\_libraries and target\_include\_directories?

4. Which test is the best?
