10
add_library(target1 funtion.c target1.c )
add_library(target2 funtion.c target2.c )
add_executable(main.out main.c) 
target_link_libraries(main.out target1 target2 ${LDFLAGS})

Here is my CMakeLists.txt above.

Both targets need to use the source file function.c. It is able to run though. My concern is that maybe it is not a good behavior for writing CMakeList.txt?

Samuel
  • 803
  • 8
  • 17

2 Answers2

3

It's totally fine to use the same source file whatever number of times. Sometimes it's even necessary, if you want to compile the same source with different pre-processor/compiler flags.

But if you are concerned with compilation time, you could:

  • move funtion.c to separate static library and link target1 and target2 libraries against it.
  • Use object library for function.c and archive output object file to target1 and target2.
ivaigult
  • 6,198
  • 5
  • 38
  • 66
  • Would it cause duplicated symbol if main.out link targe1 and target2, which both use function.c ? – Samuel Dec 28 '17 at 02:24
  • Yes, this will lead to symbol duplication. Then you'd better to use the first option (to move `function.c` to separate library and link `target1` and `target2` against it). CMake will take care that `function` is linked only once to your `main.out` – ivaigult Dec 28 '17 at 07:55
  • I did on my project option 1. That caused non-weak symbols not being properly linked vs weak symbols. So I did option 2. Now I have a problem with multiple definitions of the same function. I think there's no good solution to that... – VIPPER Apr 25 '21 at 17:58
-1

Either you have not given enough information in your question or adding function.c to target1 and target2 will not work when you will link them together with main.out because you will have duplicated symbols.

If you are sure they will be no duplicated symbols (for instance because function.c is built with different compilation flags) then your example is correct.

OlivierM
  • 2,820
  • 24
  • 41