-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmake.lua
More file actions
893 lines (787 loc) · 28.9 KB
/
cmake.lua
File metadata and controls
893 lines (787 loc) · 28.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
--
-- Name: premake-cmake/cmake.lua
-- Purpose: Define the cmake action.
-- Author: Jan "GamesTrap" Schürkamp
-- Created: 2025/11/20
-- Updated: 2026/02/01
-- Copyright: (c) 2025-2026 Jan "GamesTrap" Schürkamp
--
local p = premake
local tree = p.tree
local project = p.project
local config = p.config
local fileconfig = p.fileconfig
-- CMake module
premake.modules.cmake = {}
local cmake = p.modules.cmake
local function escape(s)
if type(s) == "table" then
return table.translate(s, escape)
end
s, _ = s:gsub('\\', '\\\\')
s, _ = s:gsub('"', '\\"')
return s
end
local function hasWorkspaceMultiplePlatforms(wks)
local _platforms = {}
local platforms = {}
for cfg in p.workspace.eachconfig(wks) do
local platform = cfg.platform
if platform and not _platforms[platform] then
_platforms[platform] = true
end
end
for k, _ in pairs(_platforms) do
table.insert(platforms, k)
end
return #platforms > 1
end
local function normalizeIdentifier(identifier)
return string.gsub(identifier, "[^a-zA-Z0-9_]", "_")
end
local function getConfigName(cfg)
if cmake.multiplePlatforms then
return string.format("%s_%s", normalizeIdentifier(cfg.platform), normalizeIdentifier(cfg.buildcfg))
else
return normalizeIdentifier(cfg.buildcfg)
end
end
local function getWorkspaceConfigs(wks)
local cfgs = {}
local defaultCfg = nil
for cfg in p.workspace.eachconfig(wks) do
local name = getConfigName(cfg)
table.insert(cfgs, name)
if name == "Release" then
defaultCfg = name
end
end
if not defaultCfg then
defaultCfg = cfgs[1]
end
return cfgs, defaultCfg
end
function cmake.generateWorkspace(wks)
local oldGetDefaultSeparator = path.getDefaultSeparator
path.getDefaultSeparator = function()
return "/"
end
cmake.multiplePlatforms = hasWorkspaceMultiplePlatforms(wks)
local cfgs, defaultCfg = getWorkspaceConfigs(wks)
p.w("# generated with premake cmake")
p.w()
p.w("cmake_minimum_required(VERSION 3.10)")
p.w()
p.w("set_property(GLOBAL PROPERTY USE_FOLDERS ON)")
p.w()
-- Enforce available configurations
p.push('set(PREMAKE_BUILD_TYPES', table.concat(cfgs, '"\n"'))
for _, config in ipairs(cfgs) do
p.w('"%s"', config)
end
p.pop(')')
p.w('get_property(multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)')
p.push('if(multi_config)')
p.w('set(CMAKE_CONFIGURATION_TYPES "${PREMAKE_BUILD_TYPES}" CACHE STRING "list of supported configuration types" FORCE)')
p.pop()
p.push('else()')
p.w('set(CMAKE_BUILD_TYPE "%s" CACHE STRING "Build type of the project.")', defaultCfg)
p.w('set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "${PREMAKE_BUILD_TYPES}")')
p.push('if(NOT CMAKE_BUILD_TYPE IN_LIST PREMAKE_BUILD_TYPES)')
p.push('message(FATAL_ERROR')
p.w('"Invalid build type \'${CMAKE_BUILD_TYPE}\'.')
p.w('CMAKE_BUILD_TYPE must be any of the possible values:')
p.w('${PREMAKE_BUILD_TYPES}"')
p.pop(')')
p.pop('endif()')
p.pop('endif()')
p.w()
-- Clear default flags
p.w('set(CMAKE_MSVC_RUNTIME_LIBRARY "")')
p.w('set(CMAKE_C_FLAGS "")')
p.w('set(CMAKE_CXX_FLAGS "")')
for _, cfg in pairs(cfgs) do
p.w('set(CMAKE_C_FLAGS_%s "")', string.upper(cfg))
p.w('set(CMAKE_CXX_FLAGS_%s "")', string.upper(cfg))
end
p.w()
if wks.startproject then
p.w('set_property(GLOBAL PROPERTY VS_STARTUP_PROJECT "%s")', wks.startproject)
p.w()
end
p.w('project("%s")', wks.name)
-- Project list
local tr = p.workspace.grouptree(wks)
p.tree.traverse(tr, {
onleaf = function(n)
local prj = n.project
--Build a relative path from the workspace file to the project file
local prjPath = p.filename(prj, ".cmake")
prjPath = path.getrelative(prj.workspace.location, prjPath)
p.w('include(%s)', prjPath)
end,
})
p.w()
path.getDefaultSeparator = oldGetDefaultSeparator
end
local function cppDialectToCMake(cppDialect)
if cppDialect == "C++98" or cppDialect == "gnu++98" then
return "98"
elseif cppDialect == "C++11" or cppDialect == "C++0x" or cppDialect == "gnu++0x" or cppDialect == "gnu++11" then
return "11"
elseif cppDialect == "C++14" or cppDialect == "C++1y" or cppDialect == "gnu++1y" or cppDialect == "gnu++14" then
return "14"
elseif cppDialect == "C++17" or cppDialect == "C++1z" or cppDialect == "gnu++1z" or cppDialect == "gnu++17" then
return "17"
elseif cppDialect == "C++20" or cppDialect == "C++2a" or cppDialect == "gnu++2a" or cppDialect == "gnu++20" then
return "20"
elseif cppDialect == "C++23" or cppDialect == "C++2b" or cppDialect == "gnu++2b" or cppDialect == "gnu++23" then
return "23"
elseif cppDialect == "C++26" or cppDialect == "C++2c" or cppDialect == "gnu++2c" or cppDialect == "gnu++26" then
return "26"
end
return ""
end
local function cDialectToCMake(cDialect)
if cDialect == "C89" or cDialect == "C90" or cDialect == "gnu89" or cDialect == "gnu90" then
return "90"
elseif cDialect == "C99" or cDialect == "gnu99" then
return "99"
elseif cDialect == "C11" or cDialect == "gnu11" then
return "11"
elseif cDialect == "C17" or cDialect == "gnu17" then
return "17"
elseif cDialect == "C23" or cDialect == "gnu23" then
return "23"
end
return ""
end
local function cppDialectToCMakeCXXExtensions(cppDialect)
return iif(cppDialect == "gnu++98" or
cppDialect == "gnu++0x" or
cppDialect == "gnu++11" or
cppDialect == "gnu++1y" or
cppDialect == "gnu++14" or
cppDialect == "gnu++1z" or
cppDialect == "gnu++17" or
cppDialect == "gnu++2a" or
cppDialect == "gnu++20" or
cppDialect == "gnu++2b" or
cppDialect == "gnu++23" or
cppDialect == "gnu++2c" or
cppDialect == "gnu++26", "TRUE", "FALSE")
end
local function cDialectToCMakeCExtensions(cDialect)
return iif(cDialect == "gnu89" or
cDialect == "gnu90" or
cDialect == "gnu99" or
cDialect == "gnu11" or
cDialect == "gnu17" or
cDialect == "gnu23", "TRUE", "FALSE")
end
local function isEmpty(t)
for _, _ in pairs(t) do
return false
end
return true
end
local oneExpression = "one_expression"
local tableExpression = "table_expression"
local function generatorExpression(prj, callback, mode)
local common = nil
local byCfg = {}
for cfg in project.eachconfig(prj) do
local settings = callback(cfg)
if not common then
common = table.arraycopy(settings)
else
common = table.intersect(common, settings)
end
byCfg[cfg] = settings
end
for cfg in project.eachconfig(prj) do
byCfg[cfg] = table.difference(byCfg[cfg], common)
if isEmpty(byCfg[cfg]) then
byCfg[cfg] = nil
end
end
commonStr = table.implode(common or {}, "", "", " ")
if isEmpty(byCfg) then
if mode == tableExpression then
return common, true
else
return commonStr, true
end
end
if #commonStr > 0 then
commonStr = commonStr .. " "
end
if mode == oneExpression then
local res = ''
local suffix = ''
for cfg, settings in pairs(byCfg) do
res = res .. string.format('$<IF:$<CONFIG:%s>,%s,', getConfigName(cfg), escape(commonStr .. table.implode(settings, "", "", " ")))
suffix = suffix .. '>'
end
return res .. suffix, false
else
local res = {}
for cfg, settings in pairs(byCfg) do
res = table.join(res, table.translate(settings, function(setting) return string.format('$<$<CONFIG:%s>:%s>', getConfigName(cfg), escape(setting)) end))
end
if mode == tableExpression then
return table.join(common, res), false
else
return commonStr .. table.implode(res, "", "", " "), false
end
end
end
local function getFiles(cfg)
local prj = cfg.project
local files = {}
table.foreachi(prj._.files, function(node)
if node.flags.ExcludeFromBuild then
return
end
local fileCfg = p.fileconfig.getconfig(node, cfg)
local rule = p.global.getRuleForFile(node.name, prj.rules)
if p.fileconfig.hasFileSettings(fileCfg) then
if fileCfg.compilebuildoutputs then
for _, output in ipairs(fileCfg.buildoutputs) do
table.insert(files, string.format('%s', output))
end
end
elseif rule then
local environ = table.shallowcopy(fileCfg.environ)
if rule.propertydefinition then
p.rule.prepareEnvironment(rule, environ, cfg)
p.rule.prepareEnvironment(rule, environ, fileCfg)
end
local ruleCfg = p.context.extent(rule, environ)
for _, output in ipairs(ruleCfg.buildoutputs) do
table.insert(files, string.format('%s', output))
end
elseif not node.generated then
table.insert(files, string.format('${CMAKE_CURRENT_LIST_DIR}/%s', node.path))
end
end)
return files
end
local function unquote(s)
if type(s) == "table" then
return table.translate(s, unquote)
end
s, _ = s:gsub('"', '')
return s
end
local function getCompiler(cfg)
local default = iif(cfg.system == p.WINDOWS, "msc", "clang")
local toolset, toolsetVersion = p.tools.canonical(_OPTIONS.cc or cfg.toolset or default)
if not toolset then
error("Invalid toolset '" .. (_OPTIONS.cc or cfg.toolset) .. "'")
end
return toolset
end
local function translateCommandsAndPaths(cmds, basedir, map)
map = map or os.shell()
local translateFunction = function(value)
local result = path.join("${CMAKE_CURRENT_LIST_DIR}", value)
result = os.translateCommandAndPath(result, map)
if value:endswith('/') or value:endswith('\\') or -- if original path ends with a slash then ensure the same
value:endswith('/"') or value:endswith('\\"') then
result = result .. '/'
end
return result
end
local processOne = function(cmd)
local replaceFunction = function(value)
value = value:sub(3, #value - 1)
return '"' .. translateFunction(value) .. '"'
end
return string.gsub(cmd, "%%%[[^%]\r\n]*%]", replaceFunction)
end
if type(cmds) == "table" then
local result = {}
for i = 1, #cmds do
result[i] = processOne(cmds[i])
end
return os.translateCommands(result, map)
else
return os.translateCommands(processOne(cmds), map)
end
end
local function generatePreBuild(prj)
local prebuildCommands, sameOutputByCfg = generatorExpression(prj, function(cfg)
local res = {}
if cfg.prebuildmessage or #cfg.prebuildcommands > 0 then
if cfg.prebuildmessage then
table.insert(res, translateCommandsAndPaths("{ECHO} " .. quote(cfg.prebuildmessage), cfg.project.location))
end
res = table.join(res, translateCommandsAndPaths(cfg.prebuildcommands, cfg.project.location))
end
return res
end, tableExpression)
if #prebuildCommands == 0 then
return
end
p.w('# pre build commands')
local commands = {}
if not sameOutputByCfg then
for i, command in ipairs(prebuildCommands) do
local variableName = string.format("PREBUILD_COMMAND_%s_%i", prj.name, i)
p.w('SET(%s %s)', variableName, command)
commands[i] = '"${' .. variableName .. '}"'
end
else
commands = prebuildCommands
end
-- add_custom_command PRE_BUILD runs just before generating the target
-- so instead, use add_custom_target to run it before any rule (as obj)
p.push('add_custom_target(prebuild-%s', prj.name)
for _, command in ipairs(commands) do
p.w('COMMAND %s', command)
end
if not sameOutputByCfg then
p.w('COMMAND_EXPAND_LISTS')
end
p.pop(')')
p.w('add_dependencies(%s prebuild-%s)', prj.name, prj.name)
end
local function generatePreLink(prj)
local prelinkCommands, sameOutputByCfg = generatorExpression(prj, function(cfg)
local res = {}
if cfg.prelinkmessage or #cfg.prelinkcommands > 0 then
if cfg.prelinkmessage then
table.insert(res, translateCommandsAndPaths("{ECHO} " .. quote(cfg.prelinkmessage), cfg.project.location))
end
res = table.join(res, translateCommandsAndPaths(cfg.prelinkcommands, cfg.project.location))
end
return res
end, tableExpression)
if #prelinkCommands == 0 then
return
end
p.w('# pre link commands')
local commands = {}
if not sameOutputByCfg then
for i, command in ipairs(prelinkCommands) do
local variableName = string.format("PRELINK_COMMAND_%s_%i", prj.name, i)
p.w('SET(%s %s)', variableName, command)
commands[i] = '"${' .. variableName .. '}"'
end
else
commands = prelinkCommands
end
p.push('add_custom_command(TARGET %s PRE_LINK', prj.name)
for _, command in ipairs(commands) do
p.w('COMMAND %s', command)
end
if not sameOutputByCfg then
p.w('COMMAND_EXPAND_LISTS')
end
p.pop(')')
end
local function generatePostBuild(prj)
local postbuildCommands, sameOutputByCfg = generatorExpression(prj, function(cfg)
local res = {}
if cfg.postbuildmessage or #cfg.postbuildcommands > 0 then
if cfg.postbuildmessage then
table.insert(res, translateCommandsAndPaths("{ECHO} " .. quote(cfg.postbuildmessage), cfg.project.location))
end
res = table.join(res, translateCommandsAndPaths(cfg.postbuildcommands, cfg.project.location))
end
return res
end, tableExpression)
if #postbuildCommands == 0 then
return
end
p.w('# post build commands')
local commands = {}
if not sameOutputByCfg then
for i, command in ipairs(postbuildCommands) do
local variableName = string.format("POSTBUILD_COMMAND_%i_%s", i, prj.name)
p.w('SET(%s %s)', variableName, command)
commands[i] = '"${' .. variableName .. '}"'
end
else
commands = postbuildCommands
end
p.push('add_custom_command(TARGET %s POST_BUILD', prj.name)
for _, command in ipairs(commands) do
p.w('COMMAND %s', command)
end
if not sameOutputByCfg then
p.w('COMMAND_EXPAND_LISTS')
end
p.pop(')')
end
local function generateBuildOptions(prj)
local buildOptions = generatorExpression(prj, function(cfg) return unquote(cfg.buildoptions) end, tableExpression)
if #buildOptions > 0 then
p.w('# build options')
p.push('target_compile_options("%s" PRIVATE', prj.name)
for _, option in ipairs(buildOptions) do
p.w('%s', option)
end
p.pop(')')
end
end
local function generateDependencies(prj)
local dependencies = project.getdependencies(prj)
if #dependencies > 0 then
p.w('# dependencies')
p.push('add_dependencies("%s"', prj.name)
for _, dependency in ipairs(dependencies) do
p.w('"%s"', dependency.name)
end
p.pop(')')
end
end
local function generateExternalIncludeDirectories(prj)
local externalIncludeDirs = generatorExpression(prj, function(cfg) return cfg.externalincludedirs end, tableExpression)
if #externalIncludeDirs > 0 then
p.w('# external include directories')
p.push('target_include_directories("%s" SYSTEM PRIVATE', prj.name)
for _, dir in ipairs(externalIncludeDirs) do
p.w('%s', path.join("${CMAKE_CURRENT_LIST_DIR}", path.getrelative(prj.location, dir)))
end
p.pop(')')
end
end
local function generateIncludeDirectories(prj)
local includeDirs = generatorExpression(prj, function(cfg) return cfg.includedirs end, tableExpression)
if #includeDirs > 0 then
p.w('# include directories')
p.push('target_include_directories("%s" PRIVATE', prj.name)
for _, dir in ipairs(includeDirs) do
p.w('%s', path.join("${CMAKE_CURRENT_LIST_DIR}", path.getrelative(prj.location, dir)))
end
p.pop(')')
end
end
local function generateForceIncludeDirectories(prj)
local forceIncludes = generatorExpression(prj, function(cfg) return getCompiler(cfg).getforceincludes(cfg) end)
if #forceIncludes > 0 then
p.w('# force include directories')
p.push('target_compile_options("%s" PRIVATE', prj.name)
for _, forceInclude in ipairs(forceIncludes) do
p.w('%s', forceInclude)
end
p.pop(')')
end
end
local function generateFrameworkDirectories(prj)
local frameworkDirs = generatorExpression(prj, function(cfg) return getCompiler(cfg).getincludedirs(cfg, {}, {}, cfg.frameworkdirs, cfg.includedirsafter) end)
if #frameworkDirs > 0 then
p.w('# framework directories')
p.push('target_compile_options("%s" PRIVATE', prj.name)
for _, frameworkDir in ipairs(frameworkDirs) do
p.w('%s', frameworkDir)
end
p.pop(')')
end
end
local function RemovePrefixes(arr, prefixes)
for idx, val in ipairs(arr) do
local found = false
for _1, prefix in ipairs(prefixes) do
if found == false and val:startswith(prefix) then
found = true
arr[idx] = val:sub(#prefix + 1)
end
end
end
return arr
end
local function generateDefines(prj)
local defines = generatorExpression(prj, function(cfg) return escape(RemovePrefixes(getCompiler(cfg).getdefines(cfg.defines, cfg), {'/D', '-D'})) end, tableExpression)
if #defines > 0 then
p.w('# defines')
p.push('target_compile_definitions("%s" PRIVATE', prj.name)
for _, define in ipairs(defines) do
p.w('%s', define)
end
p.pop(')')
end
end
local function generateUndefines(prj)
local undefines = generatorExpression(prj, function(cfg) return escape(RemovePrefixes(getCompiler(cfg).getundefines(cfg.undefines, cfg), {'/U', '-U'})) end)
if #undefines > 0 then
p.w('# undefines')
p.push('target_compile_options("%s" PRIVATE', prj.name)
for _, undefine in ipairs(undefines) do
p.w('%s', undefine)
end
p.pop(')')
end
end
local function generateCStd(prj)
if not project.isc(prj) then
return
end
local cDialect = generatorExpression(prj, function(cfg) return {cDialectToCMake(cfg.cdialect)} end, oneExpression)
if #cDialect > 0 then
p.w('# c standard')
local extensions = generatorExpression(prj, function(cfg) return {cDialectToCMakeCExtensions(cfg.cdialect)} end, oneExpression)
p.push('set_target_properties("%s" PROPERTIES', prj.name)
p.w('C_STANDARD %s', cDialect)
p.w('C_STANDARD_REQUIRED YES')
p.w('C_EXTENSIONS %s', extensions)
p.pop(')')
end
end
local function generateCPPStd(prj)
if not project.iscpp(prj) then
return
end
local cppDialect = generatorExpression(prj, function(cfg) return {cppDialectToCMake(cfg.cppdialect)} end, oneExpression)
if #cppDialect > 0 then
p.w('# c++ standard')
local extensions = generatorExpression(prj, function(cfg) return {cppDialectToCMakeCXXExtensions(cfg.cppdialect)} end, oneExpression)
p.push('set_target_properties("%s" PROPERTIES', prj.name)
p.w('CXX_STANDARD %s', cppDialect)
p.w('CXX_STANDARD_REQUIRED YES')
p.w('CXX_EXTENSIONS %s', extensions)
p.pop(')')
end
end
local function generateCFlags(prj)
if not project.isc(prj) then
return
end
local cFlags = generatorExpression(prj, function(cfg) return table.translate(getCompiler(cfg).getcflags(cfg), function(s) return string.format('$<$<COMPILE_LANGUAGE:C>:%s>', s) end) end, tableExpression)
if #cFlags > 0 then
p.w('# c flags')
p.push('target_compile_options("%s" PRIVATE', prj.name)
for _, flag in ipairs(cFlags) do
p.w(flag)
end
p.pop(')')
end
end
local function generateCPPFlags(prj)
if not project.iscpp(prj) then
return
end
local cxxFlags = generatorExpression(prj, function(cfg) return table.translate(getCompiler(cfg).getcxxflags(cfg), function(s) return string.format('$<$<COMPILE_LANGUAGE:CXX>:%s>', s) end) end, tableExpression)
if #cxxFlags > 0 then
p.w('# c++ flags')
p.push('target_compile_options("%s" PRIVATE', prj.name)
for _, flag in ipairs(cxxFlags) do
p.w(flag)
end
p.pop(')')
end
end
local function generateLinkDirectories(prj)
local libdirs = generatorExpression(prj, function(cfg) return cfg.libdirs end, tableExpression)
if #libdirs > 0 then
p.w('# link directories')
p.push('target_link_directories("%s" PRIVATE', prj.name)
for _, libdir in ipairs(libdirs) do
p.w('"%s"', libdir)
end
p.pop(')')
end
end
local function generateLinkLibraries(prj)
local libs = generatorExpression(prj, function(cfg)
local toolset = getCompiler(cfg)
local isClangOrGCC = toolset == p.tools.clang or toolset == p.tools.gcc
local useLinkGroups = isClangOrGCC and cfg.linkgroups == p.ON
local res = {}
if useLinkGroups or #config.getlinks(cfg, "dependencies", "object") > 0 or #config.getlinks(cfg, "system", "fullpath") > 0 then
-- Do not use toolset here as CMake needs to resolve dependency chains
if useLinkGroups then
table.insert(res, '-Wl,--start-group')
end
for _, link in ipairs(config.getlinks(cfg, "dependencies", "object")) do
table.insert(res, link.project.name)
end
if useLinkGroups then
-- System libraries don't depend on the project
table.insert(res, '-Wl,--end-group')
table.insert(res, '-Wl,--start-group')
end
for _, link in ipairs(config.getlinks(cfg, "system", "fullpath")) do
if link:find("/", nil, true) then
link = path.join("${CMAKE_CURRENT_LIST_DIR}", link)
end
table.insert(res, link)
end
if useLinkGroups then
table.insert(res, '-Wl,--end-group')
end
return res
end
return {}
end, tableExpression)
if #libs > 0 then
p.w('# link libraries')
p.push('target_link_libraries("%s"', prj.name)
for _, lib in ipairs(libs) do
p.w('%s', lib)
end
p.pop(')')
end
end
local function generateLinkerOptions(prj)
local allLinkOptions = generatorExpression(prj, function(cfg)
local toolset = getCompiler(cfg)
return table.join(toolset.getldflags(cfg), cfg.linkoptions) end, tableExpression)
if #allLinkOptions > 0 then
p.w('# linker options')
p.push('target_link_options("%s" PRIVATE', prj.name)
for _, linkOption in ipairs(allLinkOptions) do
p.w('%s', linkOption)
end
p.pop(')')
end
end
local function generatePrecompiledHeader(prj)
if prj.system ~= p.WINDOWS then
return
end
--MSVC uses special compiler flags for the PCH header/source file
--GCC/Clang compile the PCH like every other source file
local pchData = {}
local idx = 0
for cfg in project.eachconfig(prj) do
if cfg.enablepch ~= p.OFF then
local prjcfg, filecfg = p.config.normalize(cfg)
local pchHeaderFile = prjcfg.pchheader
local pchSrcFile = cfg.pchsource
if pchHeaderFile ~= nil and pchSrcFile ~= nil then
pchSrcFile = path.join("${CMAKE_CURRENT_LIST_DIR}", path.getrelative(prj.location, pchSrcFile))
local pchOutFile = path.join("${CMAKE_CURRENT_LIST_DIR}", path.getrelative(prj.location, path.join(cfg.objdir, pchHeaderFile .. ".pch")))
idx = idx + 1
pchData[idx] = {pchHeader = pchHeaderFile, pchSrc = pchSrcFile, pchOut = pchOutFile, cfgName = cfg.name}
end
end
end
if idx <= 0 then
return
end
p.w('# pre compiled header')
p.w('# create pre compiled header')
local first = true
for _, pchCfg in ipairs(pchData) do
if first then
first = false
p.push('if(CMAKE_BUILD_TYPE STREQUAL "%s")', pchCfg.cfgName)
else
p.push('elseif(CMAKE_BUILD_TYPE STREQUAL "%s")', pchCfg.cfgName)
end
p.push('set_source_files_properties(')
p.w("%s", pchCfg.pchSrc)
p.w("PROPERTIES")
p.w('COMPILE_OPTIONS /Yc"%s"', pchCfg.pchHeader)
p.w('COMPILE_OPTIONS /Fp"%s"', pchCfg.pchOut)
p.pop(')')
p.pop('')
end
p.pop('endif()')
first = true
p.w('# use pre compiled header')
for _, pchCfg in ipairs(pchData) do
if first then
first = false
p.push('if(CMAKE_BUILD_TYPE STREQUAL "%s")', pchCfg.cfgName)
else
p.push('elseif(CMAKE_BUILD_TYPE STREQUAL "%s")', pchCfg.cfgName)
end
p.push('target_compile_options("%s" PRIVATE', prj.name)
p.w('/Yu"%s"', pchCfg.pchHeader)
p.w('/Fp"%s"', pchCfg.pchOut)
p.pop(')')
p.pop('')
end
p.pop('endif()')
end
local function generateOutputDirectories(prj)
p.w('# output directories')
p.push('set_target_properties("%s" PROPERTIES', prj.name)
for cfg in project.eachconfig(prj) do
-- Multi-configuration generators appends a per-configuration subdirectory
-- to the specified directory (unless a generator expression is used)
-- for XXX_OUTPUT_DIRECTORY but not for XXX_OUTPUT_DIRECTORY_<CONFIG>
local binDir = path.join("${CMAKE_CURRENT_LIST_DIR}", path.getrelative(prj.location, cfg.buildtarget.directory))
local configName = getConfigName(cfg):upper()
p.w('ARCHIVE_OUTPUT_DIRECTORY_%s "%s"', configName, binDir)
p.w('LIBRARY_OUTPUT_DIRECTORY_%s "%s"', configName, binDir)
p.w('RUNTIME_OUTPUT_DIRECTORY_%s "%s"', configName, binDir)
end
p.pop(')')
end
local function generateSourceFiles(prj)
p.w('# source files')
local srcFiles = generatorExpression(prj, getFiles, tableExpression)
if #srcFiles > 0 then
p.push('target_sources("%s" PRIVATE', prj.name)
for _, file in ipairs(srcFiles) do
p.w('%s', file)
end
p.pop(')')
end
end
function cmake.generateProject(prj)
if not project.isc(prj) and not project.iscpp(prj) then
return
end
local oldGetDefaultSeparator = path.getDefaultSeparator
path.getDefaultSeparator = function()
return "/"
end
p.generate(prj, ".cmake", function(prj)
if prj.kind == "Utility" then
return
elseif prj.kind == "StaticLib" then
p.w('add_library("%s" STATIC)', prj.name)
elseif prj.kind == "SharedLib" then
p.w('add_library("%s" SHARED)', prj.name)
else
if prj.executable_suffix then
p.w('set(CMAKE_EXECUTABLE_SUFFIX "%s")', prj.executable_suffix)
end
p.w('add_executable("%s")', prj.name)
end
-- Executable/Library name
p.w('# executable/library name')
p.w('set_target_properties("%s" PROPERTIES OUTPUT_NAME %s)', prj.name, generatorExpression(prj, function (cfg) return {cfg.buildtarget.basename} end, oneExpression))
generateOutputDirectories(prj)
generateSourceFiles(prj)
--Compiler
generateBuildOptions(prj)
generateDependencies(prj)
generateExternalIncludeDirectories(prj)
generateIncludeDirectories(prj)
generateForceIncludeDirectories(prj)
generateFrameworkDirectories(prj)
generateDefines(prj)
generateUndefines(prj)
generateCStd(prj)
generateCPPStd(prj)
generateCFlags(prj)
generateCPPFlags(prj)
--Linker
generateLinkDirectories(prj)
generateLinkLibraries(prj)
generateLinkerOptions(prj)
--PCH
generatePrecompiledHeader(prj)
--Other
generatePreBuild(prj)
generatePreLink(prj)
generatePostBuild(prj)
p.w()
end)
path.getDefaultSeparator = oldGetDefaultSeparator
end
function cmake.cleanWorkspace(wks)
p.clean.file(wks, "CMakeLists.txt")
end
function cmake.cleanProject(prj)
p.clean.file(prj, prj.name .. ".cmake")
end
include("_preload.lua")
return cmake