ttroy50 / cmake-examples

Useful CMake Examples
http://ttroy50.github.io/cmake-examples
MIT License
12.45k stars 2.5k forks source link

What's the meaning of add_library (*** ALIAS ***) #70

Open kuazhangxiaoai opened 3 years ago

kuazhangxiaoai commented 3 years ago

add_library(hello::library ALIAS hello_library)

why must to use alias name for hello_library? Can I not use the alias name?

ttroy50 commented 3 years ago

It provides an alternative way to reference a target name in other parts of your cmake files.

In that example you have

add_library(hello_library SHARED
    src/Hello.cpp
)
add_library(hello::library ALIAS hello_library)

hello::library refers to the same library as hello_library but gives it a different name.

One good use case that I have found for this is in the target_link_libraries command. If you use an alias target like

target_link_libraries(hello_binary
    PRIVATE
        hello::library
)

and some some reason the hello::library target doesn't exist you will get a failure. If instead you had used

target_link_libraries(hello_binary
    PRIVATE
        hello_library
)

And you didn't have a hello_library target, than you could accidentally link a library libhello_library.so that already exists on your filesystem.

ttroy50 commented 3 years ago

Here is a link to the cmake documentation on alias targets

https://cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#alias-targets

nevalsar commented 1 year ago

@ttroy50 I don't believe this is a valid use case for this feature... The accidental linking can directly be avoided using the original hello_library itself by linking it like so:

target_link_libraries(hello_binary
    PRIVATE
        hello_library::hello_library
)

If the target isn't found, this would fail (which is what we want) instead of looking for a library in the filesystem.